Writing User CRUD API Feature Test in Laravel

Laravel empowers developers to build efficient and robust APIs effortlessly. Feature testing is an indispensable aspect of ensuring the reliability and functionality of our APIs, especially when it involves user CRUD operations. In this blog post, we’ll take a step-by-step journey through the code to feature test a User CRUD API in Laravel.

Step 1: Setting Up the Test Environment

Create a test class file with the following command.

php artisan make:test UserCrudApiTest

The test class file created can be found at tests/Feature/UserCrudApiTest.php and codes are as follows.

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserCrudApiTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

Step 2: Define and modify the Test Class

Import necessary classes and traits. And remove default test_example method.

<?php

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

class UserCrudApiTest extends TestCase
{
    use RefreshDatabase;
}

The `UserCrudApiTest` class is declared, extending `TestCase` and using `RefreshDatabase` for database isolation.

`RefreshDatabase` ensures a clean database state for each test, and `TestCase` is the base test case class. `User` is imported to create and interact with user models.

Step 3: Testing User Creation

public function test_user_can_be_created()
{
    $userData = [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => bcrypt('password123'),
    ];

    $response = $this->json('POST', '/api/users', $userData);

    $response->assertStatus(201)
             ->assertJson([
                 'name' => 'John Doe',
                 'email' => 'john@example.com',
             ]);

    $this->assertDatabaseHas('users', [
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ]);
}

This method tests the creation of a user. The `$this->json(‘POST’, ‘/api/users’, $userData)` line sends a POST request to create a user with the specified data. Assertions ensure a successful response, correct JSON structure, and that the user is stored in the database.

Step 4: Testing User Retrieval

public function test_user_can_be_retrieved()
{
    $user = factory(User::class)->create();

    $response = $this->json('GET', "/api/users/{$user->id}");

    $response->assertStatus(200)
             ->assertJson([
                 'name' => $user->name,
                 'email' => $user->email,
             ]);
}

This method tests the retrieval of a user. A user is created using the factory, and a GET request is made to fetch the user’s details. Assertions verify a successful response and the correctness of the returned data.

Step 5: Testing User Update

public function test_user_can_be_updated()
{
    $user = factory(User::class)->create();

    $updateData = [
        'name' => 'Updated Name',
        'email' => 'updated.email@example.com',
    ];

    $response = $this->json('PUT', "/api/users/{$user->id}", $updateData);

    $response->assertStatus(200)
             ->assertJson($updateData);

    $this->assertDatabaseHas('users', [
        'id' => $user->id,
        'name' => 'Updated Name',
        'email' => 'updated.email@example.com',
    ]);
}

This method tests updating a user’s details. A user is created, and a PUT request updates the user’s data. Assertions check for a successful response, the correctness of the returned JSON, and the updated data in the database.

Step 6: Testing User Deletion

public function test_user_can_be_deleted()
{
    $user = factory(User::class)->create();

    $response = $this->json('DELETE', "/api/users/{$user->id}");

    $response->assertStatus(204);

    $this->assertDatabaseMissing('users', ['id' => $user->id]);
}

This method tests the deletion of a user. A user is created, and a DELETE request is made to delete the user. Assertions ensure a successful response and confirm that the user is no longer present in the database.

After writing the necessary test methods, we can test with the following artisan command.

php artisan test --filter UserCrudApiTest

This command uses the --filter option to specify a particular test class, in this case, UserCrudApiTest. Only the tests within the UserCrudApiTest class will be executed.

The --filter option can also be used to run specific methods within a test class. For example:

php artisan test --filter UserCrudApiTest::test_user_can_be_created

Also php artisan test can be used to run all the tests in the application (all test files under tests dir).

Conclusion

Feature testing User CRUD operations in a Laravel API provides confidence in the functionality and reliability of the endpoints. Each step, from setup to testing each CRUD operation, contributes to a robust testing suite that helps maintain a high standard of code quality in our Laravel applications.

Hope you enjoy that.

Asahi



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム