问题描述
我尝试在 CakePHP 中设置一个 Json 响应视图。 我多次阅读文档 https://book.cakephp.org/4/en/views/json-and-xml-views.html,但找不到返回特定响应代码的解决方案。
这是我目前的代码
$customers = $this->Customers->find('all')->where(['organisation_id' =>1] )->contain($this->contain)->toArray();
$this->set('customers',$customers);
$this->viewbuilder()->setoption('serialize','customers');
$this->viewbuilder()->setClassName('Json');
return $this->response->withStatus(400)->withType('json')->withStringBody(json_encode($customers));
但是使用此代码您无法为其编写测试。我希望有人对此有解决方案。
解决方法
我不明白为什么不能为后一种变体编写测试。您的测试不应该关心实现细节,它们应该只测试请求返回的响应。
话虽如此,您可以配置响应而不必从控制器返回它们,只需将它们重新设置在控制器的属性上:
$this->response = $this->response->withStatus(400);
,
您绝对可以测试该自定义代码和正文,例如:
$this->get('/customers/yourfunction.json');
$this->assertResponseCode(400); // Check for the custom response code
$this->assertResponseContains('{"customers":'); // Checks for the start of the JSON body,but you can check the response body is as expected any number of ways