agyanadda@gmail.com

Laravel Testing

Advanced Laravel 1 min read Updated Dec 2, 2026 Topic 29 of 31

Automated tests check that your app still works after every change, so you catch bugs before your users do.

Types of tests

  • Feature tests (tests/Feature) — send a request to a route and check the response, database, redirects
  • Unit tests (tests/Unit) — test one small class or function on its own

Laravel supports PHPUnit and Pest. The examples here use PHPUnit.

Create and run

  • php artisan make:test PostTest — a feature test
  • php artisan make:test PriceTest --unit — a unit test
  • php artisan test — run all tests

Helpful tools

  • use RefreshDatabase; — a clean database for each test (set the test database in phpunit.xml)
  • Factories — User::factory()->create()
  • $this->actingAs($user) — log in as a user
  • $this->get('/posts'), $this->post('/posts', [...])

Common assertions

assertOk(), assertStatus(403), assertRedirect('/login'), assertSee('Hello'), assertSessionHasErrors('title'), assertDatabaseHas('posts', [...]).

Start small: test login, your main forms, and permission rules.

Example

Example — Testing post creation PHP
<?php
namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PostTest extends TestCase
{
    use RefreshDatabase;

    public function test_guests_are_redirected_to_login(): void
    {
        $this->get('/posts/create')->assertRedirect('/login');
    }

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

        $this->actingAs($user)
            ->post('/posts', ['title' => 'My test post', 'body' => 'Hello'])
            ->assertRedirect('/posts');

        $this->assertDatabaseHas('posts', ['title' => 'My test post', 'user_id' => $user->id]);
    }

    public function test_title_is_required(): void
    {
        $this->actingAs(User::factory()->create())
            ->post('/posts', ['title' => '', 'body' => 'Hello'])
            ->assertSessionHasErrors('title');
    }
}

php artisan test runs the three tests and prints PASS for each, e.g. "✓ user can create a post". If someone breaks the validation later, test_title_is_required fails.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which trait gives each test a clean database?

Exercise 2 True / False

actingAs($user) lets a test act as a logged-in user.

Exercise 3 Fill in the Blank

Run all tests with php artisan ___

Frequently Asked Questions

Both run on the same engine and work well with Laravel. Pest has a shorter, more readable syntax; PHPUnit is the classic style you will see in most older projects. Pick one per project and stay consistent.