![](/img/trans.png)
[英]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.