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?

3 Answers 3

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();
}
0
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.

1
  • This is no longer supported in PHPUnit 7
    – SeanJA
    Commented Feb 26, 2019 at 18:09
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.