【问题标题】:cakephp test post bodycakephp 测试帖子正文
【发布时间】: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


【解决方案1】:

我用

$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 输入更加困难。

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 2020-05-08
    • 2015-12-19
    • 2019-05-20
    • 1970-01-01
    • 2017-02-02
    • 2016-07-28
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多