问题描述
我正在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","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,在这种情况下如何正确测试?
解决方法
好的,经过几分钟的调试,我将断言更改为此
$response->assertJson([
'status' => 404
]);
然后我得到了预期的结果。