How to mock authentication user on unit test in Laravel?

When you start write some unit test case, like create post or need some authenticate operation, but you must to face some situation: “how to mock authentication user in test case?”

This is solution:

In Laravel, Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers, Taylor put some very helpful method in here.

actingAs

be

actingAs is a very powerful method, Introduction in official site, “The actingAs helper method provides a simple way to authenticate a given user as the current user”.

public function testApplication()
{
$user = factory(App\User::class)->create();

$this->actingAs($user)
->withSession(['foo' => 'bar'])
->visit('/')
->see('Hello, '.$user->name);
}

But here is a problem, I don’t want to create user in test case for every time, I just need a “fake” user in my test case.

You can consider to use “be” method, so how to do this?

firstly you need to instance user object and set attributes to user.

$user = new User([
'id' => 1,
'name' => 'yish'
]);

Here is a tips, you *MUST* to set fillable attribute ‘id’, because we just make fake user, not for real.

protected $fillable = [
'id', 'name', 'email', 'password',
];

And now, we get a fake user, next we need authenticate it.

$this->be($user);

That’s awesome, we can move to class TestCase for all test case and we can give a name, like this:

public function loginWithFakeUser()
{
$user = new User([
'id' => 1,
'name' => 'yish'
]);

$this->be($user);
}

When we need to authenticated user we can call loginWithFakeUser to pretend user.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.