PHPUnit Mock Method Multiple Calls with Different Arguments
Handling dynamic return values based on input arguments in a mock object requires shifting from static expectation definitions to conditional logic within your test setup. When you have a class like DB with a method Query(string $query), the standard approach of defining a single expectation often fails because it binds a specific return value to a specific call signature. If you attempt to chain multiple expectations using shouldReceive('Query')->with('SELECT *...')->andReturn(...)->once(), you quickly run into limitations if the test needs to handle different SQL strings returning different datasets, or if the same string is queried multiple times with varying results.
The core issue lies in how PHP's mocking libraries track interactions. When an expectation is defined with a specific argument using with('SELECT * FROM users'), the mock will only satisfy that call if the exact string (or a match based on your configured matcher) is passed. If you define two separate expectations for the same method name but different arguments, PHPUnit's Mockery or PHPStan-based mocks can handle this, but they require precise ordering and argument matching strategies.
To achieve multiple calls with different arguments returning distinct values, you must leverage the shouldReceive chain in a way that defines a sequence of expected interactions. Consider a scenario where your test simulates a complex database transaction. You might expect the first call to retrieve user details, followed by a second call that fetches associated orders.
$mockDb = Mockery::mock('DB');
// First call: Select users
$mockDb->shouldReceive('Query')
->with('SELECT * FROM users WHERE id = 1')
->andReturn(['id' => 1, 'name' => 'Alice']);
// Second call: Select orders for that user
$mockDb->shouldReceive('Query')
->with('SELECT * FROM orders WHERE user_id = 1')
->andReturn([
['order_id' => 101, 'total' => 50.00],
['order_id' => 102, 'total' => 75.50]
]);
// Third call: Maybe a different query or same query with different params?
$mockDb->shouldReceive('Query')
->with('SELECT * FROM users WHERE id = 2') // Different input
->andReturn(['id' => 2, 'name' => 'Bob']);
In this example, the mock is programmed to respond differently depending on the SQL string passed. The critical detail here is that these expectations are processed in a first-in-first-out (FIFO) manner. The shouldReceive chain effectively creates a queue of expected calls. When your code under test invokes $mockDb->Query('SELECT * FROM users WHERE id = 1'), PHPUnit checks the top of the queue. If the argument matches, it returns the value and removes that expectation from the queue.
If you try to pass an argument that doesn't match any remaining expectation in the queue, or if you exceed the number of defined expectations for a specific argument pattern, you will encounter an ExpectationFailedException. This is often a source of confusion during debugging. Developers sometimes assume that mocking libraries automatically handle "any SQL query" by default, but unless you explicitly define a fallback or use a wildcard matcher (like shouldReceive('Query')->with(...)->andReturnUsing(...)), the mock is strict.
One common pitfall involves using andReturnUsing for dynamic responses based on arguments. While chaining static returns works well for specific known queries, andReturnUsing allows you to inject logic that inspects the $query argument and decides what to return programmatically. This is useful if your production code uses prepared statements with bound parameters, making exact string matching difficult in tests.
$mockDb->shouldReceive('Query')
->andReturnUsing(function ($query) {
// Inspect $query inside the closure
if (strpos($query, 'users') !== false) {
return ['id' => 1];
}
return [];
});
However, using closures adds complexity to reading the test setup. If your goal is simply to verify that different queries yield different results during a specific sequence, sticking to explicit with arguments and chained returns is usually clearer and more maintainable. It forces you to explicitly document the contract between your application logic and the database layer in the test itself.
If you find yourself needing to mock a library where exact string matching of SQL is impractical or undesirable, consider injecting a custom assertion or using a matcher that ignores specific parts of the string. But for standard unit testing scenarios, defining distinct expectations for distinct argument sets remains the most robust pattern.
