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?

2 Answers 2

1

You have to use setUp function, like this:

public function setUp()    
{
    $this->mock = Mockery::mock('myMockedClass');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Have you actually tried this? It didn't work for me. Same as with using the constructir.
Of Course. Checkout the documentation of PHPUnit phpunit.de/manual/3.7/en/fixtures.html
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();
}

6 Comments

Well i have tried using setUp and also using constructor but making sure i call the parent constructor. Neither work for me.
See my edited post, I think this could be the cause of your problem.
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.
I do stuff like that a million times, so that should work. Can you post the full code of your testCase in a gist?
After some further experimenting I found that setUp works if I call parent::setUp() first. This is unfortunately not indicated in the phpunit docs.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.