How to Test Laravel Application: Simple Guide with Examples
To test a Laravel application, use
PHPUnit with Laravel's built-in testing features like php artisan test. Write test methods inside classes extending Tests\TestCase using assertions to check your app's behavior.Syntax
Laravel tests are PHP classes inside the tests/ directory. Each test class extends Tests\TestCase. Test methods start with test or have the @test annotation. Use assertion methods like $this->assertTrue() or $this->assertEquals() to verify outcomes.
Run tests with php artisan test or vendor/bin/phpunit.
php
<?php namespace Tests\Feature; use Tests\TestCase; class ExampleTest extends TestCase { public function test_basic_test() { $this->assertTrue(true); } }
Example
This example shows a simple feature test that checks if the home page loads successfully with a 200 status code.
php
<?php namespace Tests\Feature; use Tests\TestCase; class HomePageTest extends TestCase { public function test_home_page_returns_success() { $response = $this->get('/'); $response->assertStatus(200); } }
Output
OK (1 test, 1 assertion)
Common Pitfalls
- Not setting up the test database or environment correctly can cause failures.
- Forgetting to run migrations or seeders before tests leads to missing data.
- Using
assertTruewithout descriptive messages can make debugging harder. - Running tests without clearing caches or config can cause stale data issues.
php
<?php // Wrong: No database setup, no assertions public function test_user_creation() { // Missing database migration or seeding $user = User::create(['name' => 'Test']); // No assertion here } // Right: Use RefreshDatabase trait and assert use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\Models\User; class UserTest extends TestCase { use RefreshDatabase; public function test_user_creation() { $user = User::factory()->create(['name' => 'Test']); $this->assertDatabaseHas('users', ['name' => 'Test']); } }
Quick Reference
- Run tests:
php artisan test - Test directory:
tests/ - Test classes: Extend
Tests\TestCase - Common traits:
RefreshDatabasefor clean DB state - Assertions:
assertStatus(),assertDatabaseHas(),assertTrue()
Key Takeaways
Use Laravel's built-in testing tools with PHPUnit by running tests via 'php artisan test'.
Write test methods inside classes extending 'Tests\TestCase' and use assertions to verify behavior.
Set up your test environment properly with migrations and seeders to avoid false failures.
Use traits like 'RefreshDatabase' to keep tests isolated and reliable.
Check HTTP responses, database state, and application logic with Laravel's expressive assertions.