【问题标题】:Laravel Test Inaccurate ResultLaravel 测试结果不准确
【发布时间】:2020-12-16 00:12:50
【问题描述】:

我正在我的 laravel 应用程序中测试我的 api 路由,我很困惑为什么 laravel 测试总是不准确。为了模拟 404 状态码,我用不存在的路由创建了一个测试,但它总是返回 200 状态码。

 public function testTicketsLists()
{
    $user = factory(User::class)->create();
    $response = $this->actingAs($user, 'web')->withSession(['foo' => 'bar'])->get("api/{$this->endpoint}/ticketss");
    $response
        ->assertStatus(404);
    // $response->dump();
}


 Expected status code 404 but received 200. Failed asserting that 404 is identical to 200.

ticketss 端点不存在,所以我希望是 404 状态代码

api.php

   /*
|---------------------------------------------------------------------------
| services
|---------------------------------------------------------------------------
 */
// get all client api methods
Route::get('services/methods', 'Api\ServicesController@methods');
// get service lists
Route::get('services/lists', 'Api\ServicesController@serviceLists');
// get service details by id per client 
Route::get('services/{id}/details', 'Api\ServicesController@details');
// all service ids
Route::get('services/serviceids', 'Api\ServicesController@serviceids');
/*

更新,我做了一些调试,现在我明白为什么它不返回 404 响应了

    Illuminate\Testing\TestResponse^ {#8672
    +baseResponse: Illuminate\Http\JsonResponse^ {#7923
#data: "{"message":"Page Not Found","status":404,"error":true}"
#callback: null
#encodingOptions: 0
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag^ {#7924
  #computedCacheControl: array:2 [
    "no-cache" => true
    "private" => true
  ]
  #cookies: []
  #headerNames: array:5 [
    "cache-control" => "Cache-Control"
    "date" => "Date"
    "content-type" => "Content-Type"
    "x-ratelimit-limit" => "X-RateLimit-Limit"
    "x-ratelimit-remaining" => "X-RateLimit-Remaining"
  ]
  #headers: array:5 [
    "cache-control" => array:1 [
      0 => "no-cache, private"
    ]
    "date" => array:1 [
      0 => "Thu, 27 Aug 2020 06:38:52 GMT"
    ]
    "content-type" => array:1 [
      0 => "application/json"
    ]
    "x-ratelimit-limit" => array:1 [
      0 => 60
    ]
    "x-ratelimit-remaining" => array:1 [
      0 => 59
    ]
  ]
  #cacheControl: []
}
#content: "{"message":"Page Not Found","status":404,"error":true}"
#version: "1.1"
#statusCode: 200
#statusText: "OK"
#charset: null
+original: array:3 [
  "message" => "Page Not Found"
  "status" => 404
  "error" => true
]
+exception: null
}
#streamedContent: null
}

statusCode 始终为 200,在这种情况下如何正确测试?

【问题讨论】:

  • 你也应该包括你的路线

标签: laravel phpunit


【解决方案1】:

好的,经过几分钟的调试,我把断言改成了这个

   $response->assertJson([
        'status' => 404
    ]);

然后我得到了预期的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-01
    • 2015-05-10
    • 1970-01-01
    • 2017-11-28
    • 2013-11-19
    • 2023-04-10
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多