📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework Testing in Laravel

Testing in Laravel

6 min read Quiz at the end
Test with RefreshDatabase, actingAs(), postJson(), assertDatabaseHas(), and assertUnauthorized().

Testing with PHPUnit in Laravel

php artisan make:test PostControllerTest

class PostControllerTest extends TestCase {
    use RefreshDatabase;  // reset DB between tests

    public function test_authenticated_user_can_create_post(): void {
        $user = User::factory()->create();

        $response = $this->actingAs($user)
            ->postJson("/api/posts", [
                "title" => "Test Post",
                "body"  => "Test body content",
            ]);

        $response->assertStatus(201)
                 ->assertJsonStructure(["data" => ["id", "title"]]);

        $this->assertDatabaseHas("posts", ["title" => "Test Post"]);
    }

    public function test_guest_cannot_create_post(): void {
        $this->postJson("/api/posts", ["title" => "Test"])
             ->assertUnauthorized();
    }
}
Topic Quiz · 3 questions

Test your understanding before moving on

1. Which trait resets the database between tests?
💡 RefreshDatabase migrates fresh before each test.
2. Which method simulates an authenticated user?
💡 actingAs($user) sets the given user as authenticated for the test.
3. What does assertDatabaseHas() check?
💡 assertDatabaseHas("table", ["col"=>"val"]) verifies a DB record exists.