Laravel 单元测试-模拟认证的用户

在 Laravel 编写单元测试时常常会遇到须要模拟认证用户的时候,好比新建文章、建立订单等,那么在 Laravel unit test 中如何来实现呢?php

官方解决方法

Laravel 的官方文档中的测试章节中有提到:api

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:session

<?php

use App\User;

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

        $response = $this->actingAs($user)
                         ->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}
复制代码

其实就是使用 Laravel Testing Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers Trait 中的 actingAsbe 方法。ide

设置之后在后续的测试代码中,咱们能够经过 auth()->user() 等方法来获取当前认证的用户。单元测试

伪造认证用户

在官方的示例中有利用 factory 来建立一个真实的用户,可是更多的时候,咱们只想用一个伪造的用户来做为认证用户便可,而不是经过 factory 来建立一个真实的用户。测试

在 tests 目录下新建一个 User calss:this

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {
    protected $fillable = [
        'id', 'name', 'email', 'password',
    ];
}
复制代码

必须在 $fillable 中添加 id attribute . 不然会抛出异常: Illuminate\Database\Eloquent\MassAssignmentException: idspa

接下来伪造一个用户认证用户:code

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

 $this->be($user,'api');
复制代码

后续会继续写一些单元测试小细节的文章,欢迎关注 : )cdn

讨论交流

iBrand联系咱们
相关文章
相关标签/搜索