laravelphpunit

Reset auto increment (id) when running test suite?


Lets say I have this test:

class test extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function test_ids_example()
    {
        $courses = factory(Post::class, 3)->create();
        $this->assertEquals([1, 2, 3], $courses->pluck('id')->toArray());
    }

    /** @test */
    public function test_ids_example_2()
    {
        $courses = factory(Post::class, 4)->create();
        $this->assertEquals([1, 2, 3, 4], $courses->pluck('id')->toArray());
    }
}

When I run the the test one by one, it passes.. but when I run the whole test file I get this error:

test::test_ids_example_2
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
-    0 => 1
-    1 => 2
-    2 => 3
-    3 => 4
+    0 => 4
+    1 => 5
+    2 => 6
+    3 => 7
 )

Because the tests doesn't reset the auto increment "id" even though I added "RefreshDatabase" trait. How to solve this? How can I rest the id for each test?


Solution

  • 1- using DB::statement in test class's setUp() method:

    protected function setUp(): void
    {
       parent::setUp();
       DB::statement('ALTER TABLE YourTableName AUTO_INCREMENT = 1');
    }
    

    2- Using DatabaseMigrations trait (slower)

    use DatabaseMigrations;
    

    Note: RefreshDatabase trait, for database connections like MySQL/PostgreSQL/..., will use a transaction-based approach. It rolls back all database changes after each test method to reset the state quickly and efficiently.