SelrahcD
SelrahcD

Reputation: 416

How to ensure that a method exists in the real object when mocked?

I would like my test to fail if I mock an interface using Mockery and use a shouldReceive with a non-existing method. Looking around didn't help.

For instance :

With an interface :

interface AInterface {
    public function foo();
    public function bar();
}

And a test case :

function testWhatever{
    Mockery::mock('AInterface')->shouldReceive('bar');
    $this->assertTrue(true);
}

The test will pass.

Now, refactoring time, bar method is not needed in one place (let's say it's needed on several places) and is suppressed from the interface definition but the test will still pass. I would like it to fail.

Is it possible to do such a thing using mockery (and to be able to do the same thing with a class instead of an interface) ? Or does a workaround exist with some other tool or a testing methodology ?

Not sur if this can be understood as is, will try to make a clearer description of the issue if needed.

Upvotes: 2

Views: 777

Answers (2)

Eugene M
Eugene M

Reputation: 1307

To ensure that Mockery doesn't allow you to mock methods that don't exist, put the following code in your PHPUnit bootstrap file (if you want this behavior for all tests):

\Mockery::getConfiguration()->allowMockingNonExistentMethods(false);

If you just want this behavior for a specific test case, put the code in the setUp() method for that test case.

Check this section of the Mockery manual on Github for more information.

Upvotes: 4

Rodrigo Gauzmanf
Rodrigo Gauzmanf

Reputation: 2527

If you want to make sure that the method is called only one time, you can use once().

Suppose that the class AImplementation, implements the interface AInterface, and you wanna tested that the method is called, an example could be:

Mockery::mock('AImplementation')->shouldReceive('bar')->once();

You can also use: zeroOrMoreTimes(), twice() or times(n), checkout the repo at github. Also, I recommend you this tutorial by Jeffrey W

Upvotes: -1

Related Questions