【问题标题】:Laravel 6 Unit Testing Responses 401Laravel 6 单元测试响应 401
【发布时间】:2019-10-18 09:18:21
【问题描述】:

我正在使用基于令牌的操作。 Project 中的 Edit 操作请求在 Postman 中运行良好。

public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project->project_name = request('project_name');
        $project->project_description = request('project_description');
        $project->save();
        return response()->json([
            'message' =>  "Project Updated Successfully",
            'updatedId' => $project->id
            ], 200);
    }

但是在单元测试中没有得到正确的响应

 public function testBasicExample()
    {
        $response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi......'
        ])->json('POST', '/api/updateProject/1',
                ['project_name' => 'Sally'],
                ['project_description' => 'testing the api']
                );

                $response->assertStatus(200);
                $response->assertJson(['status' => true]);
    }

错误显示

PS D:\XMAPP\htdocs\minidmsapi> ./vendor/bin/phpunit
PHPUnit 8.4.1 by Sebastian Bergmann and contributors.

..F.                                                                4 / 4 (100%)

Time: 516 ms, Memory: 18.00 MB

There was 1 failure:

1) Modules\Projects\Tests\Unit\ProjectTest::testupdate
Expected status code 200 but received 401.
Failed asserting that false is true.

D:\XMAPP\htdocs\minidmsapi\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:166
D:\XMAPP\htdocs\minidmsapi\Modules\Projects\Tests\Unit\ProjectTest.php:35

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.

为什么单元测试会出现错误响应 401?

任何人,请向我解释单元测试中的实际错误和解决方案是什么。

【问题讨论】:

    标签: api unit-testing testing laravel-6


    【解决方案1】:

    你已经过去了

    ['project_description' => 'testing the api']
    

    $headers$headers 呼叫:

    public function json($method, $uri, array $data = [], array $headers = [])
    

    这会导致您的 Authorization 标头被覆盖。

    我认为您的意思是将第三个和第四个参数的组合作为第三个参数传递。

    $response = $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi......'
        ])
        ->json(
            'POST', 
            '/api/updateProject/1',
            [
                'project_name' => 'Sally',
                'project_description' => 'testing the api'
            ]
        );
    

    【讨论】:

    • 我试过你的代码。但是$response->assertStatus(200); $response->assertJson(['status' => true]); 这段代码出现了同样的错误。 !!!
    • 任何解决方案?
    猜你喜欢
    • 2022-01-20
    • 2019-05-29
    • 1970-01-01
    • 2021-07-23
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2019-03-24
    相关资源
    最近更新 更多