Laravel Testing Starting with Laravel feature Testing

Laravel Testing Starting with Laravel feature Testing

Posted on:December 12, 2018 at 10:00 AM

Although there is a lot of controversy surrounding testing in development, I prefer to follow testing practices. Testing a Laravel application has advantages over not testing it. In this post, I will guide you on how to create a new feature test in Laravel.

By default, Laravel provides two types of testing: unit testing and feature testing. Today, I will focus on creating a new feature test in Laravel.

To create a new feature test, you can use the php artisan command:

php artisan make:test TheNameOfYourTestFile

The above command will create a test file called TheNameOfYourTestFile in the Feature directory inside the tests folder. The file will have the following structure:

<?php

namespace Tests\Feature;

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

class TheNameOfYourTestFile extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

Now, you can define your test function. There is a default method inside the class called testExample that you can overwrite. Let’s do that-


/**
 * A basic test example.
 *
 * @return void
 */
public function testAVisitorCanSignUp()
{
    $this->assertTrue(true);
}

After saving the file, now let’s run testing. To run, you need to open the terminal and redirect to the project directory and then use the following command.

phpunit

You might be encountered an error that phpunit command not found: phpunit. So, you need to show where is php unit is located. Let do it once again-

vendor/bin/phpunit

It should show you the error or success message.

Cool. You have run your first PHP Test. Let’s dig into the next location.