I have a class I want to mock and make sure that only one of its methods was called. How can I construct such a mock object in PHPUnit? Something like
public function testSystemUnderTestOnlyInvokesFoo() {
$myMock = $this->createMock(ClassWithManyMethods::class);
$myMock->expects($this->once())->method('foo');
// Something like this
// $myMock->expects($this->never)->method($this->anyMethodExcept('foo'))
function_under_test($myMock);
}
The method
function accepts both a string and a Constraint
class. A PHPUnit test can create constraint classes with utility functions like isNull
, contains
or matches
. In the example, anyMethodExcept
translates to code like this:
public function testSystemUnderTestOnlyInvokesFoo() {
$myMock = $this->createMock(ClassWithManyMethods::class);
$myMock->expects($this->never)
->method($this->logicalNot($this->matches('foo')));
$myMock->expects($this->once())->method('foo');
function_under_test($myMock);
}
If you have several methods you want to exclude, use matchesRegex
like this:
$myMock->expects($this->never)
->method($this->logicalNot($this->matchesRegex('/foo|bar|baz/')));