【问题标题】:CakePHP PHPUnit TestingCakePHP PHP单元测试
【发布时间】:2015-11-17 15:18:03
【问题描述】:

我编写了testAdd() 方法并尝试调试当前返回nulldebug($articles) 正确显示新插入的数据的$this->Article->getInsertID();

public function testAdd() {
    $data = array(
        'Article' => array(
            'title' => 'Fourth Title',
            'content' => 'Fourth Title Body',
            'published' => '1',
            'created' => '2015-05-18 10:40:34',
            'updated' => '2015-05019 10:23:34'
        )
    );
    $this->_testAction('/articles/add', array('method' => 'post', 'data' => $data));
    $articles = $this->Article->find('first', array('order' => array('id DESC')));
    debug($articles);
    debug($this->Article->getInsertID);
    // return null. 

}

为什么$this->Article->getInsertID() 返回null

【问题讨论】:

  • 您在示例代码中写了$this->Article->getInsertID,不应该读为$this->Article->getInsertID()吗?
  • 我写了$this->assertEqual(4, $this->Article->getInsertID),它显示了“断言 4 匹配预期空值失败”错误。
  • 这是一个方法而不是一个属性! book.cakephp.org/2.0/en/models/…
  • 是的,它插入一行已发布的数据。

标签: cakephp phpunit


【解决方案1】:

getInsertID 是一个方法而不是一个属性,所以你应该使用$this->Article->getInsertID() 而不是$this->Article->getInsertID。但是,与其断言主键值(这不是一个特别可靠的测试),不如断言您刚刚插入的数据已保存到数据库中。

例如断言文章title已保存:-

public function testAdd() {
    $data = array(
        'Article' => array(
            'title' => 'Fourth Title',
            'content' => 'Fourth Title Body',
            'published' => '1',
            'created' => '2015-05-18 10:40:34',
            'updated' => '2015-05019 10:23:34'
        )
    );
    $this->_testAction('/articles/add', array('method' => 'post', 'data' => $data));
    $result = $this->Article->find('first', array('order' => array('id DESC')));
    $this->assertEqual($data['Article']['title'], $result['Article']['title']);
}

应该编写测试,以便您 100% 确定结果应该是什么。主键取决于数据库的当前状态,因此可能不一定是您在运行测试时所期望的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多