【问题标题】:Cakephp testAction() is not sending a json payload to controllerCakephp testAction() 没有向控制器发送 json 有效负载
【发布时间】:2012-07-24 22:18:46
【问题描述】:

我正在尝试测试一个接受 json 有效负载的控制器函数。

根据 testAction() 的文档,这可以通过将 $options['data'] 设置为适当的字符串来完成。它不适合我。 请参阅此处引用的文档:http://api20.cakephp.org/class/controller-test-case(请向下滚动 testAction() 部分)。

这是我的测试用例。

public function testCreate(){
    //Some code here
    $this->testAction('/shippingbatches/create', array('data' => '[3,6]', 'method' => 'post'));
    //Some more code here
}

这是我的控制器功能

public function create(){        
    debug($this->request); //This debug shows me an empty array in $this->request->data
    ob_flush();
    $order_ids = json_decode($this->request->data);
    //Some more code here
}

控制器函数的第一行显示 $this->request->data 中的一个空数组。如果从 testAction() 传递的“数据”是一个实际的数组,它就很好。但不是当它设置为字符串时(不像文档中所说的那样)。

这是调试的输出。

object(Mock_CakeRequest_ef4431a5) {
    params => array(
        'plugin' => null,
        'controller' => 'shippingbatches',
        'action' => 'create',
        'named' => array(),
        'pass' => array(),
        'return' => (int) 1,
        'bare' => (int) 1,
        'requested' => (int) 1
    )
    data => array()
    query => array(
        'case' => 'Controller\ShippingBatchesController'
    )
    url => 'shippingbatches/create'
    base => ''
    webroot => '/'
    here => '/shippingbatches/create'
}

请帮忙。

古普雷特

【问题讨论】:

    标签: cakephp testing


    【解决方案1】:

    这样传递数据时,您必须使用CakeRequest::input() 接收它。

    public function create() {
        $json = $this->request->input('json_decode', true);  
        debug($json);
    }
    

    我应该注意到,我是通过阅读 Cake 的 ControllerTestCase::testAction 测试用例发现的。阅读测试用例可以让您深入了解 Cake 的内部工作原理,并为您提供编写测试的提示。

    【讨论】:

    • 谢谢,这行得通。不过,我想知道你是如何从阅读测试中得到这个想法的......
    • 该测试使用测试应用的TestsAppsPostsController::input_data()。进去一看,我发现CakeRequest::input() 是用来抓取输入的。
    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 2013-03-23
    • 2020-03-30
    • 1970-01-01
    • 2023-02-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多