Mocking the user in Laravel controller

40 Views Asked by At

In a Controller I have code that relies on the user id

public function getMyStuff(Request $request)
{
    $user = Auth::user();
    var_dump($user->getId());  // Debug code, yields 'string(0) ""'

    $stuff = Cache::remember(self::$stuffCacheKeyPrefix . $user->getId(), 300, function () use ($request) {
        return /* Various logic here, which also involves the current user */
    });

    return response()->json($stuff);
}

Now I'm trying to write a test for this code, and I set up a user like this:

$user = Mockery::mock(User::class);
$user->shouldReceive('getId')->andReturn("123");

Now if I follow this directly up with var_dump($user->getId()); die; or similar, I get string(3) "123" back, as expected.

However, when running the request through:

$response = $this->actingAs($user)->get('/me');

Then getId() is just an empty string when called inside my controller. This leads me to believe I'm either setting the test-user up the wrong way, or that I'm calling the route the wrong way, but I don't get any further.

This is running with laravel/framwork: v8.83.27

0

There are 0 best solutions below