Database testing helps check if your app saves and reads data correctly. RefreshDatabase resets the database for each test to keep tests clean and reliable.
0
0
Database testing (RefreshDatabase) in Laravel
Introduction
When you want to test if data is saved correctly after an action.
When you need a fresh database state before each test to avoid leftover data.
When testing database queries or relationships in your Laravel app.
When you want to ensure your tests do not affect each other by sharing data.
Syntax
Laravel
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function test_example()
{
// Your test code here
}
}Use the RefreshDatabase trait inside your test class.
This trait runs migrations and rolls back changes between tests automatically.
Examples
This test creates a user and checks the users table has exactly one record.
Laravel
use RefreshDatabase;
public function test_user_creation()
{
User::factory()->create();
$this->assertDatabaseCount('users', 1);
}This test checks if a post belongs to the correct user using factories.
Laravel
use RefreshDatabase;
public function test_post_belongs_to_user()
{
$user = User::factory()->create();
$post = Post::factory()->for($user)->create();
$this->assertEquals($user->id, $post->user_id);
}Sample Program
This test uses RefreshDatabase to reset the database. It creates a user named Alice and checks if the users table contains her record.
Laravel
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; use App\Models\User; class UserTest extends TestCase { use RefreshDatabase; public function test_user_can_be_created() { User::factory()->create(['name' => 'Alice']); $this->assertDatabaseHas('users', [ 'name' => 'Alice' ]); } }
OutputSuccess
Important Notes
Make sure your database is set up for testing in phpunit.xml or .env.testing.
Using RefreshDatabase is faster than migrating from scratch if you use an in-memory SQLite database.
Do not use RefreshDatabase if you want to keep data between tests; use DatabaseTransactions instead.
Summary
RefreshDatabase resets your database for each test to keep tests independent.
It helps you test database actions safely without leftover data.
Use it by adding the trait to your test class.