简体   繁体   中英

Issue with cakePHP running unit tests

I've have the weirdest issue while trying to test something in my cakePHP 2.0 app. I have a function inside a model that queries the database to check if the app has already sent a notification in the last 25 days:

public function checkIfNotified($userId){
    $query = 'SELECT count(`user_id`) AS notify '.
        'FROM `churn_stats` '.
        'WHERE `user_id` = '. $userId.' '.
        'AND `notified` = 1 '.
        'AND TIME_TO_SEC(TIMEDIFF(NOW(),`created`)) <= 2160000 ';
        $this->log($query);
    $result = $this->query($query);
    return $result;
}

I'm doing some Unit tests to check if the method works, so I'm creating a record and trying to test it return return true like so:

$data['notified'] = 1;
$data['user_id'] = $userId;
$this->ChurnStats->create();
$this->ChurnStats->save($data);
$notified = $this->ChurnStats->checkIfNotified($userId);
print_r($notified);

After the result is (which is the wrong result since I've already inserted a row!):

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [notify] => 0
                )

        )

)

However I run the exact query generated by the code in the DB and the result is: 在此处输入图片说明

I've already lost a lot of time and I don't have any idea what's wrong :(.

After testing and checking everything it was another test function that somehow was changing the DB or the query of the next test, however the weird part was that the other test called the same query but didn't have any insert, update or delete that could modify the results or enviroment of the next test.

After checking everything it all reduced to something: Query Cache, by default CakePHP caches all the $this->query("..."); calls so the fix was quite easy: Deactivate it!

$result = $this->query($query, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM