Don*_*joe 3 rest phpunit laravel dingo-api
我有一个用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());
}
}
Run Code Online (Sandbox Code Playgroud)
同时我的API端点指向此控制器功能
private function store()
{
// This always returns null
$shortInput = Input::only("price");
$rules = [
"price" => ["required"]
];
$validator = Validator::make($shortInput, $rules);
// the code continues
...
}
Run Code Online (Sandbox Code Playgroud)
但是它总是失败,因为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);
Run Code Online (Sandbox Code Playgroud)
在Laravel 5.4及更高版本中,您可以验证标题的响应,如内容类型,如此(docs):
$this->response->assertHeader('content-type', 'application/json');
Run Code Online (Sandbox Code Playgroud)
或者对于Laravel 5.3及以下版本(docs):
$this->assertEquals('application/json', $response->headers->get('Content-Type'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2791 次 |
| 最近记录: |