[英]Are these REST HTTP response codes right, and what about the Content-Type?
[英]phpunit and http content-type
我有一個用Laravel(Dingo)構建的API,它運行得很好。 但是我在實現phpunit來測試我的API時遇到了問題
class ProductControllerTest extends TestCase
{
public function testInsertProductCase()
{
$data = array(
, "description" => "Expensive Pen"
, "price" => 100
);
$server = array();
$this->be($this->apiUser);
$this->response = $this->call('POST', '/products', [], [], $server, json_encode($data));
$this->assertTrue($this->response->isOk());
$this->assertJson($this->response->getContent());
}
}
同時我的API端點指向此控制器功能
private function store()
{
// This always returns null
$shortInput = Input::only("price");
$rules = [
"price" => ["required"]
];
$validator = Validator::make($shortInput, $rules);
// the code continues
...
}
但是它總是失敗,因為API無法識別有效負載。 Input :: getContent()返回JSON,但Input :: only()返回空白。 進一步調查這是因為如果請求有效負載的內容類型是JSON,則Input :: only()僅返回值
那么......如何設置上面的phpunit代碼以使用內容類型的application / json? 我假設它必須與$server
但我不知道是什么
編輯:我原來的想法實際上有兩個問題
謝謝堆
調用函數的第三個參數必須是您作為輸入參數發送到控制器的參數 - 在您的情況下是數據參數。
$ response = $ this-> call($ method,$ uri,$ parameters,$ cookies,$ files,$ server,$ content);
像下面的例子一樣更改你的代碼應該有效(你不必對數組進行json_encode):
$this->response = $this->call('POST', '/products', $data);
在Laravel 5.4及更高版本中,您可以驗證標題的響應,如內容類型,如此( docs ):
$this->response->assertHeader('content-type', 'application/json');
或者對於Laravel 5.3及以下版本( docs ):
$this->assertEquals('application/json', $response->headers->get('Content-Type'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.