Cakephp测试帖体


cakephp test post body

我有一个客户端软件,它在每个请求的POST-body内发送数据。在我的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 = (array)$this->request->input('json_decode', true);

。然后,您可以像往常一样使用request->data。

专业提示:您也可以将"application/x-www-form-urlencoded"和普通post组合在一起:

if (!$this->request->data) {
    // Only then manually retrieve input
    $this->request->data = (array)$this->request->input('json_decode', true);
}

这也意味着您可以简化您的测试并使用数组表示法为它们发送数据—因为在这里模拟php输入更加困难。