Can someone provide me a reference to a good PHPUnit mock guide? The one in the official documentation doesn't seem to be detailed enough. I am trying to study PHPUnit by reading the source code, but I am not familiar with the term matcher, invocation mocker, stub return, etc.
I need to know about the following:
1) How to expect multiple calls to a mock object's method, but each return a different sets of value?
$tableMock->expects($this->exactly(2))
->method('find')
->will($this->returnValue(2)); // I need the second call to return different value
2) How to expect a call to a mock object's method with multiple parameters?
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit architecture for unit testing frameworks that originated with SUnit and became popular with JUnit. PHPUnit was created by Sebastian Bergmann and its development is hosted on GitHub.
We then use the Fluent Interface that PHPUnit provides to specify the behavior for the stub. In essence, this means that you do not need to create several temporary objects and wire them together afterwards. Instead, you chain method calls as shown in the example. This leads to more readable and “fluent” code.
PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. The currently supported versions are PHPUnit 9 and PHPUnit 8.
[Note: All code samples from the sites linked, follow the links for more thorough explanations.]
The (current) PHPUnit documentation suggests using a callback or onConsecutiveCalls()
:
$stub->expects($this->any())
->method('doSomething')
->will($this->returnCallback('str_rot13'));
$stub->expects($this->any())
->method('doSomething')
->will($this->onConsecutiveCalls(2, 3, 5, 7));
with()
may contain multiple parameters:
$observer->expects($this->once())
->method('reportError')
->with($this->greaterThan(0),
$this->stringContains('Something'),
$this->anything());
Although not ask, on a related topic (and not in the PHPUnit documentation that I can find), you can use at()
to set expectations for multiple calls to a method:
$inputFile->expects($this->at(0))
->method('read')
->will($this->returnValue("3 4"));
$inputFile->expects($this->at(1))
->method('read')
->will($this->returnValue("4 6"));
$inputFile->expects($this->at(2))
->method('read')
->will($this->returnValue(NULL));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With