0

Is there a way to create a mock in the test class constructor/class setUp function such that the mock is available to all test methods?

I have tried creating in the constructor like:

public class testMocks extends PHPUnit_Framework_TestCase {

    protected $mock;

    public function __construct()
    {
        $this->mock = Mockery::mock('myMockedClass');
    }

...

But this doesn't work. If the first test passes, then all tests that assert on the mock pass even if they should fail (i.e running a shouldReceive that should fail). Any ideas?

BIOS
  • 1,655
  • 5
  • 20
  • 36

2 Answers2

1

You have to use setUp function, like this:

public function setUp()    
{
    $this->mock = Mockery::mock('myMockedClass');
}
Rodrigo Gauzmanf
  • 2,517
  • 1
  • 23
  • 26
0

You shouldn't overwrite the constructor of PHPUnit_Framework_TestCase, see my answer on #15051271 and also #17504870

You also need to call Mockery::close() on tearDown method. The close method cleans up the mockery container for your next test and runs the expectations you have setup.

public function tearDown()
{
    Mockery::close();
}
Community
  • 1
  • 1
Bram Gerritsen
  • 7,178
  • 4
  • 35
  • 45
  • Well i have tried using setUp and also using constructor but making sure i call the parent constructor. Neither work for me. – BIOS Jul 13 '13 at 12:20
  • See my edited post, I think this could be the cause of your problem. – Bram Gerritsen Jul 13 '13 at 14:39
  • Unfortunately not. I am using tearDown like your example :( Try test it yourself. Create a mock of a class in your setup and run two tests both asserting that say the mock should receive a method call. Make the first pass and write the second test so the assertion on the mock should fail (i.e expect the method to be called 10 times but only call it once). For me, both tests pass. If the first test passes, the next test passes. I would have thought this was quite common thing to want to do. – BIOS Jul 13 '13 at 14:55
  • I do stuff like that a million times, so that should work. Can you post the full code of your testCase in a gist? – Bram Gerritsen Jul 13 '13 at 14:59
  • After some further experimenting I found that setUp works if I call parent::setUp() first. This is unfortunately not indicated in the phpunit docs. – BIOS Jul 14 '13 at 20:57
  • Good it's working now, but it's very strange behaviour. If you are inheriting from `PHPUnit_Framework_TestCase` calling parent setUp wil actually execute no additional code, because the `setUp` method is just an empty method. Are you extending an abstract testcase you've written yourself? I've written lots of tests using PHPUnit and Mockery and I never need to call parent setUp to get the expectations running. – Bram Gerritsen Jul 14 '13 at 21:38