Mockery shouldReceive()->once() doesn't seem to work
Asked Answered
H

3

19

I'm trying to get Mockery to assert that a given method is called at least once.

My test class is:

use \Mockery as m;

class MyTest extends \PHPUnit_Framework_TestCase
{

    public function testSetUriIsCalled()
    {
        $uri = 'http://localhost';
        $httpClient = m::mock('Zend\Http\Client');
        $httpClient->shouldReceive('setUri')->with($uri)->atLeast()->once();
    }

}

As you can see, there's one test that (hopefully) creates an expectation that setUri will be called. Since there isn't any other code involved, I can't imagine that it could be called and yet my test passes. Can anyone explain why?

Hugh answered 16/4, 2013 at 11:11 Comment(0)
G
62

You need to call Mockery:close() to run verifications for your expectations. It also handles the cleanup of the mockery container for the next testcase.

public function tearDown()
{
    parent::tearDown();
    m::close();
}
Grannia answered 30/4, 2013 at 20:53 Comment(0)
U
2

To avoid having to call the close method in every test class, you can just add the TestListener to your phpunit config like so:

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

This approach is explained in the docs.

One thing to note from the linked docs is:

Make sure Composer’s or Mockery’s autoloader is present in the bootstrap file or you will need to also define a “file” attribute pointing to the file of the above TestListener class.

Unripe answered 27/3, 2016 at 14:58 Comment(1)
This is no longer supported in PHPUnit 7Neela
L
0

Just a sidenote: If you use Laravel: the make:test --unit generates a test class that extends the original PhpUnit Testcase class and not the included Tests\Testcase, which loads the laravel app and runs the Mockery::close(). It is also the reason why in some cases your tests fail if you use Laravel specific code (like Cache, DB or Storage) in the units you're testing.

so if you need to test units with Laravel specific code, just swap out the 'extends Testcase' and there is no need to call Mockery::close() manually

Lasala answered 15/11, 2021 at 5:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.