Laravel Unit Testing – HOW TO with Code Examples

larvavel, php framework

Welcome to our comprehensive guide on unit testing within the Laravel framework. Laravel, known for its elegant syntax and powerful features, also offers a robust testing environment, making it an excellent choice for modern web applications. This guide specifically focuses on unit testing, a software testing method where individual units of source code are tested to ascertain whether they function correctly. With Laravel’s built-in testing tools, developers can ensure their code behaves as expected, thereby improving software quality and reducing bugs.

We will delve into practical ways of implementing Laravel unit tests, showcasing code examples for a clearer understanding. Whether you are new to Laravel or looking to improve your existing Laravel skills, this guide will serve as a valuable resource. Let’s explore the world of Laravel unit testing together!

Using Data Faker in Laravel Unit Testing

Faker is a PHP library that allows developers to generate fake data for their applications, making it incredibly useful when writing unit tests in Laravel. The library is shipped with Laravel out of the box, thus it can be readily used within your applications.

When writing unit tests, you often need to create objects with specific values, but what about cases when the specific value doesn’t matter? This is where Faker comes into play. It enables you to quickly generate placeholder data that adheres to a specific format, such as names, addresses, paragraphs of text, or even specific types of numbers.

For instance, suppose you’re testing a feature that requires a user model. Instead of manually creating a user and defining all of the fields, you can use Faker to generate this data:

$user = factory(App\User::class)->create();

In this code, Laravel uses Faker behind the scenes to create a User instance with random yet valid data. You can also override specific fields if you need to:

$user = factory(App\User::class)->create([
    'name' => 'John Doe',
]);

Using Faker with Laravel’s factory system allows you to create realistic, valid data for your unit tests, helping to ensure that your application works correctly with a variety of data inputs.

See also  Use PHP to Scrape Error & Bounced Emails from the EXIM Log and Add To a Blacklist

Laravel Unit Testing Example

Here’s an example of a Laravel unit test class that could be used to validate CRUD (Create, Read, Update, Delete) operations for a hypothetical “Book” model:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Book;

class BookTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test creating a book.
     *
     * @return void
     */
    public function testCreateBook()
    {
        $book = Book::factory()->create([
            'title' => 'The Catcher in the Rye',
            'author' => 'J.D. Salinger',
            'published_year' => 1951,
        ]);

        $this->assertDatabaseHas('books', [
            'id' => $book->id,
            'title' => 'The Catcher in the Rye',
            'author' => 'J.D. Salinger',
            'published_year' => 1951,
        ]);
    }

    /**
     * Test updating a book.
     *
     * @return void
     */
    public function testUpdateBook()
    {
        $book = Book::factory()->create();

        $book->update([
            'title' => 'To Kill a Mockingbird',
            'author' => 'Harper Lee',
            'published_year' => 1960,
        ]);

        $this->assertDatabaseHas('books', [
            'id' => $book->id,
            'title' => 'To Kill a Mockingbird',
            'author' => 'Harper Lee',
            'published_year' => 1960,
        ]);
    }

    /**
     * Test deleting a book.
     *
     * @return void
     */
    public function testDeleteBook()
    {
        $book = Book::factory()->create();

        $book->delete();

        $this->assertDatabaseMissing('books', [
            'id' => $book->id,
        ]);
    }

    /**
     * Test retrieving a book.
     *
     * @return void
     */
    public function testRetrieveBook()
    {
        $book = Book::factory()->create();

        $retrievedBook = Book::find($book->id);

        $this->assertEquals($book->id, $retrievedBook->id);
        $this->assertEquals($book->title, $retrievedBook->title);
        $this->assertEquals($book->author, $retrievedBook->author);
        $this->assertEquals($book->published_year, $retrievedBook->published_year);
    }
}

In this example, the RefreshDatabase trait is used to automatically migrate and refresh the database before each test. The testCreateBook method creates a new book using Laravel’s model factory and then checks if the book was successfully inserted into the database using the assertDatabaseHas method.

The testUpdateBook method creates a new book, updates its attributes, and then checks if the updates were successfully applied to the database using the assertDatabaseHas method.

The testDeleteBook method creates a new book, deletes it, and then checks if the book was successfully removed from the database using the assertDatabaseMissing method.

See also  Mastering Laravel Many-to-Many Relationships

Finally, the testRetrieveBook method creates a new book, retrieves it using the find method, and then checks if the retrieved book matches the original book using the assertEquals method.

This is just an example of how you could test CRUD operations for a Laravel model. Depending on your specific application and requirements, you may need to customize this test class to fit your needs.

Leave a Comment