CakePHP testAction()不发送一个json有效载荷到控制器
问题描述:
我想测试一个接受json有效载荷的控制器函数。CakePHP testAction()不发送一个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
}
控制器功能的第一行是显示我在这 - $>请求 - >数据空数组。如果从testAction()传递的'data'是一个真正的数组,它会很好地出现在&中。但不是当它被设置为一个字符串(不像它在文档中所述)。
这里是调试的输出。
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'
}
请大家帮忙。
Gurpreet
答
在传递这样的数据,则必须使用CakeRequest::input()
接受它。
public function create() {
$json = $this->request->input('json_decode', true);
debug($json);
}
我要指出,我通过阅读蛋糕的测试用例ControllerTestCase::testAction
发现这一点。阅读测试用例可以让您深入了解Cake的内部工作原理,并为您提供编写测试的提示。
谢谢,这个工程。不过,我想知道你是如何从阅读测试中获得想法的... – 2012-07-26 17:52:43
该测试使用测试应用程序的'TestsAppsPostsController :: input_data()'。看看那里,我发现'CakeRequest :: input()'被用来获取输入。 – jeremyharris 2012-07-26 18:17:26