简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM