Home  >  Article  >  PHP Framework  >  Introducing Laravel unit test: Simulating authenticated users

Introducing Laravel unit test: Simulating authenticated users

藏色散人
藏色散人forward
2021-04-23 16:13:541598browse

##Laravel unit test: simulate authenticated user

When writing unit tests in Laravel, we often encounter times when we need to simulate authenticated users, such as creating new articles, creating orders, etc. So how to implement this in Laravel unit test?

Official solution

It is mentioned in the testing chapter of Laravel's official documentation:

Of course, one common use of the session is for maintaining state for the authenticated user. The actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory to generate and authenticate a user:
<?php

use App\User;

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $user = factory(User::class)->create();

        $response = $this->actingAs($user)
                         ->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}
In fact, using Laravel Testing ## The

actingAs and be methods in the #Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers Trait. After setting, in the subsequent test code, we can obtain the currently authenticated user through methods such as

auth()->user()

. Fake authenticated user

In the official example, factory is used to create a real user, but more often, we just want to use a fake user as the authenticated user. , instead of creating a real user through factory.

Create a new

User

calss in the tests directory: <pre class="brush:php;toolbar:false">use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable {     protected $fillable = [         'id', 'name', 'email', 'password',     ]; }</pre>Must add the

id

attribute in $fillable. Otherwise An exception will be thrown: Illuminate\Database\Eloquent\MassAssignmentException: idNext, forge a user authentication user:

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

 $this->be($user,'api');

I will continue to write some small details of unit tests in the future. Articles, welcome to follow: )

Related recommendations:
The latest five Laravel video tutorials

The above is the detailed content of Introducing Laravel unit test: Simulating authenticated users. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete