【发布时间】:2014-10-04 03:29:40
【问题描述】:
我有一个客户端软件,它在每个请求的 POST 正文中发送数据。在我的 CakaPHP 应用程序中,我使用以下代码访问检查数据:
// StationController.php
if ($this->request->is('post')) {
$data = json_decode(file_get_contents('php://input'), TRUE);
...
}
现在的问题是,如何编写一个测试用例来模拟具有正确正文内容的 POST 请求?这是我当前不正确的测试用例:
/**
* testPoints method
*
* @return void
*/
public function testPoints() {
$data = array(
'Station' => array('id' => '123'),
'points' => array(
array('id' => 1, 'sensor_id' => 1, 'value' => 25.43, 'sync' => 0, 'timestamp' => 1407063842),
array('id' => 2, 'sensor_id' => 2, 'value' => 52.5, 'sync' => 0, 'timestamp' => 1407063842),
array('id' => 3, 'sensor_id' => 3, 'value' => 934.566, 'sync' => 0, 'timestamp' => 1407063842),
array('id' => 4, 'sensor_id' => 4, 'value' => 867.2, 'sync' => 0, 'timestamp' => 1407063842),
array('id' => 5, 'sensor_id' => 1, 'value' => 25.93, 'sync' => 0, 'timestamp' => 1407064081),
array('id' => 6, 'sensor_id' => 2, 'value' => 53.5, 'sync' => 0, 'timestamp' => 1407064081),
array('id' => 7, 'sensor_id' => 3, 'value' => 935.566, 'sync' => 0, 'timestamp' => 1407064081),
array('id' => 8, 'sensor_id' => 4, 'value' => 665.57, 'sync' => 0, 'timestamp' => 1407064081)
)
);
$data = json_encode($data);
$result = $this->testAction(
'/stations/points/1',
array('data' => $data, 'method' => 'post')
);
debug($result);
}
如何修改 testAction 添加一些 POST 数据?
【问题讨论】:
-
注意:通常你可以直接使用
$this->request->data = $this->request->input('json_decode', true); -
我以前不知道
$this->request->input('json_decode', true);方法,这解决了我的问题。
标签: php unit-testing cakephp