Testing Laravel facades with mockery always passes, even when it should fail

喜欢而已 提交于 2019-12-24 00:57:31

问题


I'm trying to mock some facades in Laravel during unit testing, but it seems that the tests always pass no matter what.

For example, this example taken from the Laravel docs here:

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

It seems I can put that in any of the test methods and they always pass even though nothing of the sort has been done with the Event facade.

Here is the test class:

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');
    }

}

What am I missing in order to test Facades? Am I right in thinking that I should be able to call shouldReceive() on any Laravel Facade without any setup?


回答1:


You need to tell mockery to run it's verification. You can do that by putting

\Mockery::close();

Either at the end of your test method, or in your test class' teardown method.

Alternatively, you could set up mockery's phpunit integration by adding this to your phpunit.xml

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

See http://docs.mockery.io/en/latest/reference/phpunit_integration.html for further information.



来源:https://stackoverflow.com/questions/24028829/testing-laravel-facades-with-mockery-always-passes-even-when-it-should-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!