【问题标题】:Test JSON-returning controller method without MissingViewError在没有 MissingViewError 的情况下测试返回 JSON 的控制器方法
【发布时间】:2016-03-13 09:25:40
【问题描述】:

我正在测试一个只有 JSON 视图的控制器方法。我的方法按预期运行,但测试方法只返回“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。这并不能解决异常。

【问题讨论】:

    标签: unit-testing cakephp phpunit cakephp-2.0


    【解决方案1】:

    您没有发出 JSON 请求/访问 JSON 端点,因为您的请求 URL 不包含 .json 扩展名,您的请求也没有发送适当的 Accept 标头(我不记得后者是否完全可以使用 2.x 控制器测试用例类)。

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多