我有一个使用Laravel(Dingo)构建的API,它运行得很完美。然而,我在实现phpunit进行单元测试时遇到了问题。
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代码以使用content-type application / json?我假设它必须与$server有关,但我不知道是什么。
编辑: 实际上,我的原始想法有两个问题:
1. Input :: getContent()有效,因为我填充了第六个参数,但Input :: only()无效,因为我没有填充第三个参数。感谢@shaddy
2.如何在phpunit请求标头中设置内容类型仍未得到答案。
非常感谢。
return response($content, $status)->header('Content-Type', $value);
- Sh1d0w$this->response = $this->call('POST', '/products', $data, [], [], ['CONTENT_TYPE' => 'application/json']);
- Sh1d0w