Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

crnkovic's avatar

Rollback database after each test method

Hey,

I've got bunch of tests that used to run on Sqlite in memory database and it all works fine. Now that I need to run it against an actual MySQL database, errors keep on coming. I need database to be fresh (no data in it) each time a test function runs (not a test class, but each test method).

I've been using RefreshDatabase trait which does the trick. Or doesn't. I have no idea. When I run test methods individually, they all work fine. But when I run them in bulk (either entire class or the entire suite), it's all filled with errors because the data is already filled in the database. So if I seed the database in one test method, then I need the same seeder in another test method, it would try to seed twice, hence the failures. RefreshDatabase class has a refreshTestDatabase method which, in theory, should rollback everything after each tearDown (each time a test method finishes). And debugging shows that it actually runs. However, database is still not clean, it still has data in it.

Environment is simple: phpunit.xml says DB_CONNECTION is mysql. Each test that needs a database uses RefreshDatabase trait. That's it. Running Laravel 5.8.

I've been really struggling to run PHPUnit tests on MySQL. Anyone know a good way to do that? Ya need any more info?

0 likes
3 replies
obiefy's avatar

Sometimes I forget using RefreshDatabase trait in some testCase classes. so you need to make sure you are using trait at all classes.

Have you tried DatabaseTransactions?

crnkovic's avatar

Yeah, everything. Nothing seems to work. I gave up.

I was using factories to whip up new models, and then accessing like $this->post('/teams/1/invitations') but I gave up and ended up doing: $this->post('/teams/'.$team->id.'/invitations').

IDs were screwed up because of previous test runs.

bobbybouwmann's avatar

@crnkovic If you use the RefreshDatabase trait in all your tests this shouldn't be a problem since it will start a transaction for each tests and rollback the transaction after each test.

Please or to participate in this conversation.