WeBRT Română

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

  1. Introduction to automated testing
  2. Setting up the test environment
  3. Unit tests
  4. Feature tests
  5. Mocks and databases
  6. Running the tests
  7. 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.