Ramesh KC
Ramesh KC

Reputation: 582

CakePHP PHPUnit Testing

I wrote the testAdd() method and try to debug the $this->Article->getInsertID(); which currently returns null while debug($articles) correctly shows the newly inserted data.

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. 

}

Why does $this->Article->getInsertID() return null?

Upvotes: 3

Views: 69

Answers (1)

drmonkeyninja
drmonkeyninja

Reputation: 8540

getInsertID is a method not an attribute so you should use $this->Article->getInsertID() not $this->Article->getInsertID. However, rather than asserting the primary key value (which isn't an especially reliable test) assert that the data you've just inserted has saved to the database.

For example assert that the article title has saved:-

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']);
}

Tests should be written so that you are 100% sure of what the result should be. The primary key is dependent on the current status of the database so may not necessarily be what you expect at the time of running the test.

Upvotes: 3

Related Questions