Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpunit check if method was called on the tested class

Tags:

php

phpunit

Lets say i have this code block:

$i = 1;

if ($i > 1) {
    $this->methodOne();
} else {
    $this->methodTwo();
}

How can i check if methodOne or methodTwo were called from the tested class in my PHPUnit test?

like image 292
jvrnt Avatar asked Dec 24 '22 20:12

jvrnt


1 Answers

Are methodOne and methodTwo public? If yes, then you can add tests for those too to make sure they correctly work, so you assert against the other code of your method. If they are not public, then based on the output of the method in discussion you can tell which method got called.

At the end I think you're more interested in your class behaving correctly, rather than on the internal chain of called methods. Also keep in mind that unit tests should do black-box testing and should not be care about the implementation of the methods being tested.

And not lastly, asserting on methods called on $this will heavily couple your tests with the implementation of the class. Thus if you refactor the class, you'll need to also update the tests that are no longer working. And it gets harder to test if internal methods get called in the order you need.

Putting all this talk aside, it doesn't mean that what you asked about cannot be done. You can use a partial mock (https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects), and do your asserts on the partial mock instead of creating a new test object. For example:

$testedObject = $this->getMock('MyClass',array('methodOne', 'methodTwo'))

will give you an object with only methodOne and methodTwo being replaced by PHPUnit. You can then set expectations on what methods do you need called:

$testedUnit = $this->getMock('MyClass',array('methodOne', 'methodTwo'));
$testedUnit->expects($this->once())
    ->method('methodOne');
// setup the condition so that the tested method calls methodOne()
// ...
$testedUnit->testedMethod();
like image 165
Cristik Avatar answered Dec 27 '22 11:12

Cristik