Laravel PHPUnit mock Request

Laravel PHPUnit mock Request

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Laravel PHPUnit mock Request

When testing a controller method that relies on Illuminate\Http\Request, it is common to encounter friction when mocking the object. The core issue often stems from a misunderstanding of how the has() method behaves versus how the underlying data structure works, and consequently, how to configure the mock to reflect that behavior accurately.

In the scenario where you are writing a PHPUnit test for a controller, you might have code that checks for the existence of specific input fields like username or email. If your mock setup causes $request->has('username') to return the entire payload array instead of a boolean, your logic flow will break. This happens because the expectation set on the mock is too broad and does not account for the conditional nature of the has() method.

The specific problem arises from how you configure the expectations for the get() and has() methods. In your test setup, you defined an expectation for has that returns $requestParams whenever it is called. The logic inside your controller expects a boolean result—true if the key exists, false otherwise. By returning the full array, you are effectively telling the controller that the check passed, but with incorrect data types that can lead to unexpected type coercion errors or logic failures downstream.

To fix this, you need to distinguish between the raw data retrieval and the existence check. The get() method should indeed return the collection of parameters, but has() must return a boolean value based on whether the requested key is present in that collection. You cannot simply pass the same array back for every call; you must inspect the input arguments passed to the mock to determine what to return.

Here is how you can adjust your mock expectations to handle this correctly:

use Illuminate\Http\Request;
use PHPUnit\Framework\MockObject\MockObject;

public function testIndex()
{
    $request = $this->createMock(Request::class);
    
    $requestParams = [
        'username' => 'test',
        'email'    => 'test@test.com'
    ];

    // Configure 'all()' to return the full payload
    $request->method('all')
        ->willReturn($requestParams);

    // Configure 'get()' to return specific values based on the key provided
    $request->expects($this->any())
        ->method('get')
        ->with('username')
        ->willReturn('test')
        ->willReturnCallback(function ($key) use ($requestParams) {
            return $requestParams[$key] ?? null;
        });

    // Configure 'has()' to check if the key exists in the original array
    $request->expects($this->any())
        ->method('has')
        ->withConsecutive(
            ['username'],
            ['email']
        )
        ->willReturnCallback(function ($key) use ($requestParams) {
            return array_key_exists($key, $requestParams);
        });

    // Now the logic inside your controller will work as expected:
    // if ($request->has('username')) will correctly return true (bool)
}

The key takeaway here is that mocking a complex interface like Request requires mimicking its internal logic, not just its signature. When you use willReturn($requestParams) for the has() method, you are bypassing the existence check entirely. Instead, you should pass the $requestParams array into your expectation configuration and use a callback or specific with() constraints to return true only when the requested key matches an existing one in that array.

This approach ensures that if you later remove the username key from $requestParams during another test case, the mock will automatically return false for has('username'), maintaining the integrity of your test assertions without needing to manually change every expectation string. This pattern is essential for writing robust unit tests that validate both positive and negative scenarios involving conditional logic in your controllers.

Our network