AppDividend
Latest Code Tutorials

Laravel 9 Testing: How to Test Laravel Application

PHPUnit is one of the most well-known unit testing packages for PHP. It is primarily designed for unit testing, which means testing your code in the smallest components possible, but it is also incredibly flexible.

Laravel Testing

Laravel has a built-in testing module PHPUnit which is included out of the box, and a phpunit.xml file is already set up for your application. The phpunit.xml file is already configured for our Laravel application; by default, Laravel ships with two directories and two files.

  1. Feature Directory
  2. Unit Directory
  3. CreatesApplication.php
  4. TestCase.php

PHPUnit Environment

When we run the tests via PHPUnit, Laravel will automatically set the environment to test. It configures the cache and session environment to the array driver. So while testing, no session or cache data is persisted. You can see it in the below code. Go to the phpunit.xml file.

<php>
     <env name="APP_ENV" value="testing"/>
     <env name="CACHE_DRIVER" value="array"/>
     <env name="SESSION_DRIVER" value="array"/>
     <env name="QUEUE_DRIVER" value="sync"/>
</php>

Step 1: Install Laravel Testing Project

composer create-project laravel/laravel laraveltesting --prefer-dist

Now, configure the database in the .env file.

Type the following command.

php artisan migrate

It will create two tables in the database.

Now, for testing, we will create another model and migration file. So type the following command.

php artisan make:model Stock -m

It will create a stocks table also, and we need to define the schema for it.

<?php

// create_stocks_table

  /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stocks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

Next, type the below command.

php artisan migrate

It will make stocks table.

Step 2: Mass assignment exception

In the model Stock.php file, add the following property.

protected $fillable = ['name','price'];

Step 3: Make the test file.

To make a test file, there is an artisan command for it, so type in the terminal,

php artisan make:test StockTest

This will create feature test file inside tests  >>  Feature  >>  StockTest file.

Now, the file will look like this.

<?php

// StockTest.php 

namespace Tests\Feature;

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

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

The next step would be to write one simple test in the testExample() function.

<?php

// StockTest.php

namespace Tests\Feature;

use Tests\TestCase;
use App\Stock;
use Illuminate\Foundation\Testing\RefreshDatabase;

class StockTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
      $stock = new Stock(['name'=>'Tesla']);
      $this->assertEquals('Tesla', $stock->name);
    }
}

I have included our model Stock.php in the StockTest.php file and created an object to insert one stock in the array.

Remember, by default, we are using array drivers. So if I have not included the model correctly or have not added the fillable property in the model, this test will fail. Otherwise, It will pass the test.

Step 4: Run the test.

Please type the following command to run the test.

phpunit

Note: If this will throw an error, please run the following command.

vendor/bin/phpunit

or

vendor\bin\phpunit

One of these options will run your tests.

From the above example, we can see the output like this.

PHPUnit 6.3.0 by Sebastian Bergmann and contributors.
… 3 / 3 (100%)
Time: 845 ms, Memory: 10.00MB
OK (3 tests, 3 assertions)
So, we have successfully run the test. If you want to fail the test, just for fun, remove the following line from the StockTest.php file.
use App\Stock;

Now, again run the test.

PHPUnit 6.3.0 by Sebastian Bergmann and contributors.

.E. 3 / 3 (100%)

Time: 471 ms, Memory: 10.00MB

There was 1 error:

1) Tests\Feature\StockTest::testExample
Error: Class ‘Tests\Feature\Stock’ not found

L:\testingLaravel\tests\Feature\StockTest.php:17

ERRORS!
Tests: 3, Assertions: 2, Errors: 1.

The test will fail.

Finally, Laravel Unit Testing is over. Find more info at this URL: https://laravel.com/docs/9.x/testing.

This is just a phpUnit test. Other browser and HTTP tests will be in the following articles, so stay tuned. Also, we will talk about Laravel Dusk in the future.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.