Laravel测试需要身份验证的操作

时间:2020-05-25 13:50:51

标签: php laravel testing

我正在尝试为我的Laravel应用编写功能测试,但是某些操作需要登录。我该怎么做,以防止由于未登录而导致错误?我正在使用JWTAuth。

1 个答案:

答案 0 :(得分:0)

我用标头Authorization发出请求,准确地再现了现实世界中发生的事情。

我为测试用例创建一个特征,并在需要身份验证的地方使用:

在特征中,您将在标题Authorization中为用户生成JWT有效令牌。如果我将Tymon包用于JWTAuth

<?php

namespace Tests\Feature;

use JWTAuth;

trait CallApiTrait {
    /**
     * Simulate call api
     *
     * @param  string $endpoint
     * @param  array  $params
     * @param  string $asUser
     *
     * @return mixed
     */
    protected function callApi($endpoint, $method,$params = [], $email = 'user@email',$password='password')
    {
        $headers = [
            'Accept'=>'application/json',
        ];

        if($email&&$password){
            $token = $token = JWTAuth::attempt(['email'=>$email,'password'=>$password]);
            $headers['Authorization'] = 'Bearer ' . $token;
        }

        return $this->json(
            $method,
            $endpoint,
            $params,
            $headers
        );
    }

在我的测试方法中

    class StudentTest extends TestCase {
    use CallApiTrait;
    ...

    public function test_can_request_with_auth(){
        $rs = $this->callApi(route('foo.bar'),'GET');
        $rs->assertStatus(200);
    }