PHPUnit assert no method is called
15,261
Solution 1
Yes, it's quite simple, try this:
$classA->expects($this->never())->method($this->anything());
Solution 2
You can use method MockBuilder::disableAutoReturnValueGeneration
.
For example, in your test overwrite default TestCase::getMockBuilder
:
/**
* @param string $className
* @return MockBuilder
*/
public function getMockBuilder($className): MockBuilder
{
// this is to make sure, that not-mocked method will not be called
return parent::getMockBuilder($className)
->disableAutoReturnValueGeneration();
}
Advantages:
- all your mocks won't be expected to call anything than mocked methods. No need to bind
->expects(self::never())->method(self::anything())
to all of them - you still can set new mocks. After
->expects(self::never())->method(self::anything())
you can't
Works for PhpUnit v7.5.4 (and probably, later ones).
Comments
-
Jeroen De Dauw almost 2 years
I have a ClassA that uses a ServiceB. In a certain case, ClassA should end up not invoking any methods of ServiceB. I now want to test this and verity no methods are indeed called.
This can be done as follows:
$classA->expects( $this->never() )->method( 'first_method' ); $classA->expects( $this->never() )->method( 'second_method' ); ...
Is there a way to simply state "no method should be called on this object" rather then having to specify a restriction for each method?