How to Perform Testing in Laravel 11 Application

Testing in Laravel is primarily done using PHPUnit. PHPUnit is a testing framework for PHP, and Laravel provides support for it out of the box.

Let’s create a simple test for a hypothetical UserController that has a method to fetch a user by their ID.

First, let’s create a UserController:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show($id)
    {
        $user = User::find($id);

        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        return response()->json($user);
    }
}

Now, let’s create a test for this UserController:

<?php

namespace Tests\Feature;

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

class UserControllerTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function it_returns_a_user()
    {
        // Create a user
        $user = User::factory()->create();

        // Hit the endpoint
        $response = $this->json('GET', '/api/users/' . $user->id);

        // Assert the response
        $response
            ->assertStatus(200)
            ->assertJson([
                'id' => $user->id,
                'name' => $user->name,
                // Add more fields here if you have them
            ]);
    }

    /** @test */
    public function it_returns_404_if_user_not_found()
    {
        // Hit the endpoint with an invalid user id
        $response = $this->json('GET', '/api/users/999');

        // Assert the response
        $response->assertStatus(404);
    }
}

This test class contains two test methods. The first one checks if the endpoint returns the correct user data, and the second one checks if a 404 response is returned when the user is not found.

To run the test, use the following command:

php artisan test

This will execute all the tests in the tests directory. You should see output indicating whether the tests passed or failed.

This is a basic example, but Laravel provides many more features for testing such as testing API requests, form validation, middleware, and more.

Leave a Reply