Mock Auth::user() in Laravel 6

Viewed 1645

I have this code:

// ...
Passport::actingAs($this->user);
$mock = Mockery::mock(User::class);
$mock->shouldReceive('myMethodName')->andReturn(157);
Auth::shouldReceive('user')->once()->andReturn($mock);

If I call

Auth::user()->myMethodName(); // It returns 157

But if I call (or another one method of Auth)

  Auth::id();
  // it throws Mockery\Exception\BadMethodCallException : Method Mockery_2_Illuminate_Auth_AuthManager::id() does not exist on this mock object

Where is the problem ?

3 Answers

Finally I found the answer:

$this->user = factory(User::class)->create();
Passport::actingAs($this->user);

$obj = Mockery::mock($this->user)
    ->makePartial()
    ->shouldReceive('myMethodName')
    ->andReturn(123)
    ->getMock();

Auth::setUser($obj);

You should use Auth() like:

Auth::user()->id;

For newer versions of Laravel:

$user = (new User)->forceFill([
    'name' => 'Their name',
    'email' => 'email@example.com',
]);

$user->email
// output: email@example.com
Related