【问题标题】:CakePHP 4 JSON View - Return different Response Http CodeCakePHP 4 JSON 视图 - 返回不同的响应 Http 代码
【发布时间】:2021-07-29 07:44:38
【问题描述】:

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

但是使用此代码,您无法为其编写测试。我希望有人对此有解决方案。

【问题讨论】:

    标签: cakephp cakephp-4.x


    【解决方案1】:

    您绝对可以测试该自定义代码和正文,例如:

    $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
    

    【讨论】:

      【解决方案2】:

      我不明白为什么不能为后一种变体编写测试。你的测试不应该关心实现细节,他们应该只测试请求返回的响应。

      话虽如此,您可以配置响应而不必从控制器返回它们,只需将它们设置回控制器的属性:

      $this->response = $this->response->withStatus(400);
      

      【讨论】:

        猜你喜欢
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 2022-01-17
        • 2020-11-28
        • 2021-12-26
        相关资源
        最近更新 更多