CakePHP 4 JSON 视图 - 返回不同的响应 Http 代码

问题描述

我尝试在 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');

我知道我可以用这个返回一个 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...