Conditional Mock Behavior in PHPUnit
When you create a mock object, the default expectation is that every call to a mocked method returns the same static value regardless of the arguments provided. This works fine for simple scenarios, but it quickly becomes a bottleneck when your application logic depends on specific inputs triggering different behaviors. You might want methodToMock('one') to return 'value A' while methodToMock('two') returns 'value B'.
A common mistake is defining multiple expectations sequentially using with(). Consider this setup:
$mock = $this->getMock('myObject', ['methodToMock']);
// First expectation
$mock->expects($this->any())
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// Second expectation
$mock->expects($this->any())
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
This approach fails because PHPUnit does not treat these as additive rules for a single method signature. Instead, the second expectation completely overwrites the first. When the test runs and calls methodToMock('one'), PHPUnit checks the most recent definition (the one expecting 'two'), finds a mismatch, and throws an exception. You cannot simply "add" conditions to a mock object using chained expectations in this manner; the internal state of the mock is overwritten rather than extended.
Using Callbacks for Dynamic Returns
The solution lies in decoupling the return value logic from the static will() chain. PHPUnit allows you to pass a callback directly into the will() method. This callback receives the arguments passed to the mocked method, allowing you to inspect them and decide dynamically what to return.
You can use an anonymous function or a named closure. Here is how you would structure it:
$mock = $this->getMock('myObject', ['methodToMock']);
// Define a callback that inspects arguments
$callback = function ($arguments) {
$value = 'default';
// Check the first argument to determine behavior
if (isset($arguments[0]) && is_string($arguments[0])) {
if ($arguments[0] === 'one') {
$value = 'method called with argument "one"';
} elseif ($arguments[0] === 'two') {
$value = 'method called with argument "two"';
}
}
return $value;
};
// Attach the callback to the method expectation
$mock->expects($this->any())
->method('methodToMock')
->will($callback);
In this implementation, you define a single expectation with $this->any(). This tells PHPUnit: "Expect methodToMock to be called any number of times with any arguments." Inside the callback, you handle the logic. If the argument is 'one', return the specific string for 'one'. If it's 'two', return the string for 'two'. If neither matches, return a default value or throw an exception to enforce stricter testing rules.
The Role of will() vs. Callbacks
It is important to understand that will() accepts two distinct types of inputs: a static value returned by $this->returnValue() or a callback function. When you use $this->returnValue(), the return is static and tied to that specific expectation block. When you use a callback, the function executes every time the mocked method is invoked, receiving the exact arguments passed at runtime.
This pattern is particularly useful when your production code uses switch statements or complex boolean logic based on input parameters. By mirroring that logic inside the test's callback, you ensure your unit tests cover specific branches of execution without needing to manage multiple expectation blocks that overwrite each other.
Practical Considerations and Limitations
While callbacks provide immense flexibility, they introduce a trade-off in readability. A long if/else chain inside a mock callback can make the test harder to scan compared to simple returnValue() calls. If your logic is simple (e.g., just checking for 'one' vs 'two'), a callback is still cleaner than multiple expectations. However, if the logic becomes complex, you might consider extracting the return value determination into a helper method within your test class to keep the expectation chain concise.
Additionally, ensure that your callback handles edge cases gracefully. If the argument type differs from what you expect (e.g., passing an integer when expecting a string), your callback should either handle it or let PHPUnit throw its standard exception. This ensures the test fails loudly if the production code is called with invalid types, maintaining the integrity of your testing suite.
For projects built on the Laravel framework, this technique applies directly to mocking services where specific input configurations dictate different API responses. Whether you are using the legacy getMock() syntax or modern Mockery or PHPUnit 10+ standards, the principle remains the same: use callbacks to bridge the gap between static expectations and dynamic behavior.