Warning: unexpected database modification, resetting DB state

Warning: unexpected database modification, resetting DB state

by Lawrence Lagerlof -
Number of replies: 1

Hi. I am creating a unit test in Moodle for my plugin. I am receiving this error when running the test class:

"Warning: unexpected database modification, resetting DB state"

This error doesn't happen if I use $this->resetAfterTest(true); before each method. The problem: I need to keep the state of the database between the test methods.

Eg: One method to create the user, other method to create a course, a third method to put the user inside the course.



    public function test_create_user()
    {
        global $DB;
        //$this->resetAfterTest(true);
        $user = $this->getDataGenerator()->create_user();
        $this->userid = $user->id;
        $this->assertEquals(1, $DB->count_records('user', ['id' => $user->id]));
    }

Average of ratings: -
In reply to Lawrence Lagerlof

Re: Warning: unexpected database modification, resetting DB state

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
Nothing should persist between separate unit tests (if it does, then there is a bug in your tests) - it should be possible to run each test separately and get exactly the same results as running all of them together.

You can write helper functions (not called test_xx) which could be called from multiple tests, if you need common setup between tests (or use the setUp() function is you are wanting some same configuration for all of the tests in the file). But if you want to create a user and a course and then enrol the user in the course, then this all needs to be done within a single test.
Average of ratings: Useful (2)