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?”
I’m not recommend before add
id to model and fillable it, @ryan.skinner discribe the reason and nicer see
next, @alozynskiy post a new way to do this:
$user = new User();
This is solution:
Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers, Taylor put some very helpful method in here.
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()
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([
Here is a tips, you MUST to set fillable attribute ‘id’, because we just make fake user, not for real.
protected $fillable = [
And now, we get a fake user, next we need authenticate it.
That’s awesome, we can move to class TestCase for all test case and we can give a name, like this:
public function loginWithFakeUser()
When we need to authenticated user we can call loginWithFakeUser to pretend user.