测试 JSON- 返回没有 MissingViewError 的控制器方法

Test JSON-returning controller method without MissingViewError

我正在测试只有 JSON 视图的控制器方法。我的方法按预期运行,但测试方法只有 returns "MissingViewException"。有没有办法在单元测试中避免这个异常(除了在 View/People/map_leads.ctp 插入一个空文件)?

PeopleController.php

public function mapLeads($territory_id = null) {
    $leads = $this->Person->getPeople([
        'territory_id' => $territory_id
    ]);
    $this->set('leads', $leads);
}

AppController.php

public $components = ['RequestHandler'];

routes.php

Router::parseExtensions('json');

PeopleControllerTest.php

public function testMapLeads() {
    $id = 40;
    $result = $this->testAction('/people/mapLeads/' . $id, array('return' => 'vars'));
}

View/People/json/map_leads.ctp 存在并被 CakePHP 正确使用;只是测试想看View/People/map_leads.ctp.

我查看了 CakePHP: calling testAction to a json-returning method causes missing view exception 提醒关于​​将 RequestHandler 添加到 $components。这不会解决异常。

在您的操作中写入此代码。

$this->autoLayout = false; $this->autoRender = false; $this->response->type('application/javascript');

您没有发布 JSON request/accessing JSON 端点,因为您的请求 URL 不包含 .json 扩展名,也不包含 .json 扩展名您的请求发送适当的 Accept header(我完全不记得 2.x 控制器测试用例 class 是否可以实现后者)。

使用 .json 扩展,你应该会很好。

$this->testAction('/people/mapLeads/' . $id . '.json', array('return' => 'vars'));