【问题标题】:How to unit test views with helper functions in laravel如何在 laravel 中使用辅助函数对视图进行单元测试
【发布时间】:2017-01-06 08:09:52
【问题描述】:

我有这些测试用例访问 url 并检查正确的行为,但我无法使其工作,因为它在视图中的辅助函数上出错。

它适用于浏览器,但不适用于测试。

    /** @test */
    public function setUp()
    {
        parent::setUp();

    }

    /** @test **/   
    public function openAdminDashboardUnauthorized()
    {    
        $crawler = $this->client->request('GET', 'admin/organizations');
        $this->assertTrue($this->client->getResponse()->isOk());

    }

    /** @test **/
    public function tearDown()
    {
        parent::tearDown();            
    }

这是错误

编辑 我的帮助类加载在 classLoader 的 global.php 中 顺便说一句,这是在 laravel 4.2 上

更新

人们说您必须模拟辅助函数才能对它们进行单元测试。但在我的情况下,辅助函数在视图中,我测试了从设置函数转储静态消息,实际上它在测试运行时没有加载。

【问题讨论】:

    标签: php laravel unit-testing laravel-4 helper


    【解决方案1】:

    使用Mockery,laravel4.2默认有。见https://laravel.com/docs/4.2/testing 你应该在顶部有这样的东西。

    use Mockery as m;
    
    class ClassToTest
    {
        public function test_some_method()
        {
            // Mock view helper
            $viewHelperMock = m::mock(ViewHelper::class);
    
            // Set expectations
            $viewHelperMock->shouldReceive('show');
            ...
    
            // This must be done only after setting the expectations
            $this->app->instance(ViewHelper::class, $viewHelperMock);
    
            ...
            // Your assertions goes here
            }
    }
    

    我们将我们自己的 viewHelperMock 实例绑定到 Laravel 的 DI 容器。因此,每当对 ViewHelper 类发出请求时,它都会解析为我们的模拟实例。因此,现在您可以为视图助手中调用的所有方法设置期望值。

    如果您向我们展示您的视图 (html) 代码,那么指导您会更容易。不要生气,一开始会很棘手和令人困惑。所以,多试几次,看看Laravel's IOC container 是如何工作的。

    如果您有任何问题,请告诉我们。

    【讨论】:

      【解决方案2】:

      这就是我发现的工作。

      在 composer.json 自动加载子树中加载了我的助手类

      并快速运行“composer dump-autoload”

      "autoload": {
              "classmap": [
                  "app/commands",
                  "app/controllers",
                  "app/models",
                  "app/database/migrations",
                  "app/database/seeds",
                  "app/tests/TestCase.php"
              ],
              "files": [
                  "app/helper/Helper.php"
              ]
          }
      

      现在我知道了在 global.php 中加载类和通过 composer 自动加载的区别。如果有人能详细解释 laravel 启动应用程序的顺序,我会接受。

      【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      相关资源
      最近更新 更多