3

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?

4
  • 1
    You've written $this->Article->getInsertID in your example code, should it not read $this->Article->getInsertID()? Commented Aug 24, 2015 at 9:51
  • 1
    I wrote $this->assertEqual(4, $this->Article->getInsertID) and it shows the `Failed asserting that 4 matches expected null' errors. Commented Aug 24, 2015 at 9:57
  • 2
    It is a method not an attribute! book.cakephp.org/2.0/en/models/… Commented Aug 24, 2015 at 9:59
  • 1
    Ya, It inserts a row with posted data. Commented Aug 24, 2015 at 10:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.