Performance: Database testing (RefreshDatabase)
This concept affects test execution speed and database state consistency during automated testing.
Jump into concepts and practice - no test required
use RefreshDatabase;
public function testExample() {
// Database refreshed before this test
$this->post('/api/data', [...]);
$this->assertDatabaseHas('table', [...]);
}public function testExample() {
// No database refresh
// Tests run on shared database state
$this->post('/api/data', [...]);
$this->assertDatabaseHas('table', [...]);
}| Pattern | Database Operations | Test Runtime Impact | Reliability | Verdict |
|---|---|---|---|---|
| No database refresh | No reset, shared state | Fast per test | Flaky, unreliable | [X] Bad |
| RefreshDatabase trait | Full reset per test | Slower per test | Reliable, consistent | [OK] Good |
RefreshDatabase trait in Laravel tests?RefreshDatabaseRefreshDatabase in a Laravel test class?use keyword inside the class body.use RefreshDatabase; inside the class.use keyword inside class [OK]RefreshDatabase:
public function test_user_creation() {
User::factory()->create(['name' => 'Alice']);
$this->assertDatabaseHas('users', ['name' => 'Alice']);
}
What will happen if you run this test twice in a row?RefreshDatabase effectRefreshDatabase but the database is not resetting between tests. What is the most likely cause?use RefreshDatabase;, the trait's reset logic won't run.use RefreshDatabase; trait in your test class -> Option BRefreshDatabase but also seeds some initial data before each test. Which approach is correct?$this->seed() in setUp() methodRefreshDatabase trait and call $this->seed() in the test's setUp() method -> Option AsetUp() [OK]