CakePHP PHPUnit测试

CakePHP PHPUnit测试,cakephp,phpunit,Cakephp,Phpunit,我编写了testAdd()方法,并尝试调试$this->Article->getInsertID()当前返回null,而debug($articles)正确显示新插入的数据 public function testAdd() { $data = array( 'Article' => array( 'title' => 'Fourth Title', 'content' => 'Fourth Title B

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

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

getInsertID
是一个方法而不是一个属性,所以您应该使用
$this->Article->getInsertID()
而不是
$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));
    $result = $this->Article->find('first', array('order' => array('id DESC')));
    $this->assertEqual($data['Article']['title'], $result['Article']['title']);
}

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

您已经在示例代码中编写了
$this->Article->getInsertID
,如果它不读取
$this->Article->getInsertID()
?我编写了
$this->assertEqual(4,$this->Article->getInsertID)
并显示“未能断言4个匹配预期空值”错误。这是一个方法,而不是一个属性!是的,它插入了一行已发布的数据。