Php 单元测试 401


Php unit test 401

当我尝试使用以下代码测试我的 api 时:

$client = new Client();
        $res = $client->request('POST', $this->url.'/api/v1/school/1', [
            'form_params' => [
                'currentUserId' => 1
            ]
        ]); //line 22
        $obj = json_decode($res->getBody());
        $result = $obj->{'result'}->{'message'};
        $this->assertEquals('Error', $result);

它不会比第 22 行更进一步(见评论)。当我在邮递员中发布到同一个网址时,结果是(状态代码为 401):

{
  "result": {
    "message": "Error",
    "school": "Error show school"
  }
}

但是为什么它在我的单元测试中没有走得更远呢? 当我做出 200 作为响应时,它会走得更远!

我无法评论您的问题,所以我需要在回答中提问。您在第 22 行收到哪种错误或脚本中断的原因?您是否启用了错误报告和/或检查了日志文件?

如果没有抛出错误/异常,请尝试转储$res

找到答案!您必须添加:

['http_errors' => false]

现在的方法:

$client = new Client();
        $res = $client->request('POST', $this->url.'/api/v1/school/1',['http_errors' => false], [
            'form_params' => [
                'currentUserId' => 1
            ]
        ]);

虽然杰米的回答似乎有效,但有一个非常小的细节你应该小心。如果您使用 :

$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1',['http_errors' => false], [
       'form_params' => ['currentUserId' => 1]
       ]);

就像 Jamie 的答案一样,即使您提供了错误的凭据并且您应该获得 401,您也将始终获得 200 状态代码,这就是为什么此代码永远不会阻止您的进程,但这并不意味着您检查 401 状态的动机已实现。如果你真的想检查它是否通过 phpunit 返回 401,你应该像这样使用它:

$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1',[
       'http_errors' => false,
       'form_params' => ['currentUserId' => 1]
       ]);
$status = $response->getStatusCode();
$this->assertEquals(401,$status);

这将产生正常的结果,因为它实际上会将返回的代码与 401 匹配。

我希望它很清楚并且有所帮助