PHPUnit is a testing framework for the PHP programming language, and it can be used to test Laravel applications. It provides tools for writing and running tests, asserting that the expected output matches actual results, and generating code coverage reports. To use PHPUnit with Laravel, you need to install it via Composer and then write test cases that extend the base TestCase class provided by Laravel. You can run tests using the phpunit command and use the assert methods to test the outputs of your application’s code.

## Benefits of Writing Tests for Your Application

Writing tests for your application is important for several reasons:

– **Improved reliability:** Tests help ensure that changes to your code do not break existing functionality, reducing the risk of bugs and making your application more reliable.

– **Faster development:** By having a suite of tests in place, you can make changes to your code more quickly and confidently, without having to manually check every part of your application each time.

– **Better documentation:** Tests serve as a form of documentation, describing how your application should behave and what it is expected to do.

– **Easier maintenance:** As your application evolves over time, tests help you catch breaking changes early, making maintenance and future development easier.

– **Improved code quality:** Writing tests can help you identify design problems, improve code readability, and promote best practices, leading to higher-quality code.

Overall, writing tests for your application can help you deliver a better, more reliable, and more maintainable product.

There are two types of tests.

### Unit Test

A unit test should test a single piece of functionality. They are made to ensure that a specific method (or unit) of a class performs a specific set of tasks.

### Feature Test

A feature test should hit a route; if that’s what you want, then give feedback, and the database will reflect the change you made.

To install PHPUnit via Composer, follow these steps:

Note: The above steps assume that you have Composer installed on your system. If not, please follow the instructions on the official Composer website to install it.

  1. Open your terminal and navigate to the root directory of your Laravel application.
  2. Run the following command to install PHPUnit as a development dependency:
composer require --dev phpunit/phpunit
  1. After the installation is complete, you can verify that PHPUnit is installed by running the following command:
./vendor/bin/phpunit --version

4. You should see the version of PHPUnit that you have installed.

Configuring a Testing Database in Laravel

In Laravel, you can configure a separate database for testing purposes. This helps to isolate the tests from the data in your production database and ensures that test data is not permanently stored in your production database. To configure a testing database in Laravel, you need to perform the following steps:

  1. Create a new database in your database management system that will be used specifically for testing.
  2. Update the phpunit.xml file: In the root directory of your Laravel application, open the phpunit.xml file and add the following code to the <php> section:
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>

This sets the testing environment to use an in-memory SQLite database, which is fast and ideal for testing purposes.

When you run the initial tests pre-written by Laravel using the PHP Artisan Test commands, you get something similar to the screenshot below:

Testing Laravel Applications with PHPUnit

The above output tells us that the two default tests—a unit and a feature test—ran and passed successfully.

Here’s a simple example of how to write a test using PHPUnit in Laravel:

In this example, the test class extends the base TestCase class provided by Laravel, and the testBasicTest method tests the response status code of the / route to ensure that it returns a 200 status code, indicating that the page is accessible.

  1. Create a test file in the tests directory. For example:
namespace Tests\Unit;

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

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

        $response->assertStatus(200);
    }
}

2. Run the test using the following command in the terminal:

php artisan test

Output:

Testing Laravel Applications with PHPUnit

What If Tests Fail?

For a failed test case, we are going to modify a route that is not defined in Laravel’s routes/web.php and then run the php artisan test command in the command prompt.

namespace Tests\Unit;

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

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {  
        // Modify route access
        $response = $this->get('/xyzefg');

        $response->assertStatus(200);
    }
}

Output:

Testing Laravel Applications with PHPUnit

As you can see, one assertion is marked as failed, with explanations below and arrows to the exact test line that failed the assertions. So this is how errors are shown.

Here we show a live example: Login Test

Make sure you have used Laravel Breeze for authentication.

  1. Create a new test file using the command line.
php artisan make:test LoginTest

Now you can see that the LoginTest.php file was created under the tests/Feature directory. Open this file and create a new method for testing.

namespace Tests\Feature;

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

class LoginTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    // For migrate Database from your DB to sqlite memory
    use RefreshDatabase;

    public function test_example()
    {
        // Check if the login page renders
        $response = $this->get('/login');

        $response->assertStatus(200);
    }

    // New Method for testing 
    public function test_user_login_with_email_and_password()
    {
        // Create a new user using Laravel Factory. Please use the User namespace on top of the class.
        $user = User::factory()->create();
        $this->post('login', [
            'email'    => $user->email,
            'password' => 'password',
        ]);

        $this->assertAuthenticated();
    }
}

2. Run the test using the following command in the terminal:

php artisan test --filter=LoginTest

Output:

Testing Laravel Applications with PHPUnit

Other additional articles for you

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *