<?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
. 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
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




























