Automated Testing in Laravel: From Setup to Practical Examples
This article shows how to configure and write automated tests in Laravel using PHPUnit and Pest, including practical examples of unit and feature tests.
Summary
- Introduction to automated testing
- Setting up the test environment
- Unit tests
- Feature tests
- Mocks and databases
- Running the tests
- Conclusion
Introduction to automated testing
Laravel comes with built-in testing support using PHPUnit and offers an elegant syntax for testing applications.
Setting up the test environment
The .env.testing file can be used for separate configuration.
Run the migrations for testing:
php artisan migrate --env=testing
Unit tests
Creating a unit test:
php artisan make:test OrderServiceTest --unit
Example:
public function test_order_total_is_calculated_correctly()
{
$order = new Order(['price' => 100, 'quantity' => 2]);
$this->assertEquals(200, $order->price * $order->quantity);
}
Feature tests
Creating a feature test:
php artisan make:test OrderTest
Example:
public function test_user_can_create_order()
{
$user = User::factory()->create();
$response = $this->actingAs($user)->post('/orders', [
'name' => 'Test Order'
]);
$response->assertStatus(302);
$this->assertDatabaseHas('orders', ['name' => 'Test Order']);
}
Mocks and databases
Laravel offers the RefreshDatabase trait for resetting the database:
use Illuminate\Foundation\Testing\RefreshDatabase;
For mocks:
$this->mock(OrderService::class, function ($mock) {
$mock->shouldReceive('process')->once();
});
Running the tests
php artisan test
Or using PHPUnit:
vendor/bin/phpunit
Conclusion
Automated testing in Laravel helps prevent regressions and maintain code quality, giving you confidence as the application evolves.