7

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?

1 Answer 1

13

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

I know i can mock and test the methods separately, what i'm looking for is test that methodOne is called from the tested unit itself. If im testing MainMethod() that in some scenario calls methodOne() - i want to check if it was called

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.