首页 > 解决方案 > 如何在 laravel 单元测试中模拟 api 身份验证

问题描述

enter code here我调用需要身份验证的服务,为此,我没有使用中间件特征,

$user = new User([
            'id' => 1,
            'eos_id' => '832355',
            'user_name' => 'yish',
            'email_id' => 'test@test.com'
        ]);
        $this->actingAs($user, 'api'); 

之后,当我检查为 auth('api')->check() 它总是返回 false。

编辑

我想测试的控制器方法

public function destroy($id)
    {
        try {
            $deleted = $this->wareHouseService->deleteWareHouse($id, auth('api')->user()->getAuthIdentifier());
        } catch (\Exception $e) {
            $errors = [$e->getMessage()];
            if ($e instanceof ValidationException) {
                $errors = Arr::first(array_values($e->errors()));
            }
            return (new ErrorResource(collect($errors)))
                ->response()
                ->setStatusCode(422);
        }
}

测试方法

public function test_destroy_warehoue () {

    $user = new User([
            'id' => 1,
            'whr_id' => '832355',
            'user_name' => 'yish',
            'email_id' => 'test@test.com'
        ]);

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

    $this->mockWareHouseService->shouldReceive('destroy')
            ->with(619, auth('api')->user()->getAuthIdentifier())
            ->andReturn(true);
    $actualData = $this->mockWareHouseController->destroy(619);

}

这里 auth('api')->user()->getAuthIdentifier() 是远离返回 null 。

标签: laravelunit-testingauthentication

解决方案


在您的测试方法中,您需要像模拟wareHouseService. 何时调用用户(在警卫之后)它应该返回您的用户。会是这样的;

$user = factory(User::class)->create(['id' => 2]);
Auth::shouldReceive('guard')->once()->with('api')->andReturnSelf();
Auth::shouldReceive('user')->once()->andReturn($user);

推荐阅读