【问题标题】:Testing Laravel facades with mockery always passes, even when it should fail用嘲弄来测试 Laravel 外观总是通过,即使它应该失败
【发布时间】:2014-07-24 14:17:16
【问题描述】:

我试图在单元测试期间模拟 Laravel 中的一些外观,但似乎无论如何测试总是通过。

例如,这个例子取自 Laravel 文档:

Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));

似乎我可以将它放在任何测试方法中,并且它们总是通过,即使 Event 门面没有做任何事情。

这里是测试类:

class SessionsControllerTest
extends TestCase
{    
    public function test_invalid_login_returns_to_login_page()
    {
        // All of these pass even when they should fail
        Notification::shouldReceive('error')->once()->with('Incorrect email or password.');
        Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));
        Notification::shouldReceive('nonsense')->once()->with('nonsense');

        // Make login attempt with bad credentials
        $this->post(action('SessionsController@postLogin'), [
            'inputEmail'     => 'bademail@example.com',
            'inputPassword'  => 'badpassword'
        ]);

        // Should redirect back to login form with old input
        $this->assertHasOldInput();
        $this->assertRedirectedToAction('SessionsController@getLogin');
    }

}

为了测试 Facade,我缺少什么?我是否认为我应该能够在任何 Laravel Facade 上调用 shouldReceive() 而无需任何设置?

【问题讨论】:

    标签: php unit-testing laravel mockery


    【解决方案1】:

    您需要告诉 mockery 运行它的验证。你可以这样做

    \Mockery::close();
    

    在您的测试方法结束时,或在您的测试类的拆卸方法中。

    或者,您可以通过将其添加到您的 phpunit.xml 来设置 mockery 的 phpunit 集成

    <listeners>
      <listener class="\Mockery\Adapter\Phpunit\TestListener"></listener>
    </listeners>
    

    更多信息请参见http://docs.mockery.io/en/latest/reference/phpunit_integration.html

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2015-01-25
      • 2023-03-13
      • 2021-03-03
      • 1970-01-01
      相关资源
      最近更新 更多