W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Laravel 也提供了幾個(gè)輔助函數(shù)來測試 JSON APIs 和其響應(yīng)。例如,json
,getJson
,postJson
,putJson
,patchJson
,deleteJson
,以及 optionsJson
可以被用于發(fā)送各種 HTTP 動(dòng)作。你也可以輕松地將數(shù)據(jù)和請(qǐng)求頭傳遞到這些方法中。首先,讓我們實(shí)現(xiàn)一個(gè)測試示例,
發(fā)送 POST
請(qǐng)求到 /user
,并斷言返回的期望數(shù)據(jù):
<?php
class ExampleTest extends TestCase
{
/**
* 一個(gè)基本的功能測試示例
*
* @return void
*/
public function testBasicExample()
{
$response = $this->postJson('/user', ['name' => 'Sally']);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
}
}
技巧:
assertJson
將響應(yīng)轉(zhuǎn)換為一個(gè)數(shù)組,并利用PHPUnit::assertArraySubset
來驗(yàn)證給定的數(shù)組存在于應(yīng)用返回的 JSON 響應(yīng)中。因此,如果 JSON 響應(yīng)中有其他屬性,測試仍舊會(huì)在給定數(shù)組存在的情況下通過。
此外,JSON 響應(yīng)數(shù)據(jù)可以作為數(shù)組變量在響應(yīng)上訪問:
$this->assertTrue($response['created']);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: