Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Use Laravel Unit Testing to Avoid Project-Wrecking Mistakes

August 17, 2018

7 Min Read
laravel unit testing
Reading Time: 7 minutes

What is PHPUnit?

PHPUnit is one of the most well known and highly optimized unit testing packages of PHP. It is a top choice of many developers for rectifying different developmental loopholes of the application. Its main function is to perform overall unit testing for apps, therefore, you can test your code in detail. Yet you can also use it for different functions, as it is incredibly flexible to do just more than unit testing. Moreover, it supports all major PHP frameworks including Laravel. Many expert developers recommend it for all Laravel unit testing processes, because of its optimized testing standards.

PHPUnit is developed with simple assertions, which make it pretty easier for you to test codes completely. Further it gives optimum results when you are testing code components individually, giving you magnified results, so that errors can be figure out easily. However, this means that testing much more advanced components like controllers, models and form validations can be a bit complicated as well.

Read More About: PHP Unit Testing Using PHPUnit Framework

Laravel Unit Testing
1. Unit Testing with Laravel
2. Prerequisites
3. Create Laravel Unit Test Case
4. Writing a Basic Unit Test

5. Testing Laravel Application
6. Token Mismatch Exception Error
7. Final Words

Unit Testing with Laravel

Laravel is the most popular PHP framework for application development. From the testing perspective, it is also known to be highly adequate for its creative testing features. In Laravel, there are two ways to test your app. One is with Unit testing while other is with Feature testing. Unit testing allows to test your classes models, controllers etc, while Feature testing enables you to test your code base.

If you look inside your Laravel installation directory, you can see that there are two test subdirectories available. These two subdirectories in your hosting for Laravel project are of Unit testing and Feature testing. These are the places where you will be conducting your applications test, either be Unit testing or Feature testing.

In this article, I will demonstrate the basics of Laravel PHPUnit testing. The article will demonstrate using both PHPUnit assertions and default Laravel test helpers.

Prerequisites

For the purpose of this Laravel unit testing tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.x

I have used Cloudways host Laravel on a managed server. Cloudways offers a great devstack integrated in its platform and allows me to work freely without distracting my attention to any server level issue. You can also try out Cloudways for free by signing up for an account.

Create Laravel Unit Test Case

While using PHPUnit, the first step is to create new test classes. These test classes are stored in the./tests/ directory of your Laravel application. Each test class is named as Test.php inside a folder. As this format helps PHPUnit to find each test class easily, and further ignores any other class that doesn’t resides in the Test.php file.

In your newly installed Laravel application, you will find two files in the ./tests/ directory, one of ExampleTest.php and the other TestCase.php. TestCase.php file is basically a bootstrap file which sets the Laravel environment and features within our tests. It makes easy to use Laravel features in tests, and also enables framework for the testing helpers. The ExampleTest.php constitutes an example test class which contains basic test case using app testing helpers.

For creating new test class, you can either create a new file manually, or can run the inbuilt artisan make:test command of the Laravel.

Get Your VueJS Handbook Now

Simple enter your email address and get the download link in your Inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

To create a new test class named BasicTest, you just need to run the following artisan command:

php artisan make:test BasicTest

Laravel will create a basic test class that looks like this:

<?php

class BasicTest extends TestCase

{

   /**

* A basic test example.

*

* @return void

*/

   public function testExample()

   {

       $this->assertTrue(true);

   }

}

?>

It is good to find out the default Laravel phpunit.xml file before running your test suite. PHPUnit will itself locate for the file naming phpunit.xml or phpunit.xml.dist in its current execution directory. Within this file, you can configure specific operations for your tests.

You might also like: PHP Continuous Integration With Travis CI

Though this file contains a lot of information regarding tests, but the most important section for now is the testsuite directory definition:

<?xml version="1.0" encoding="UTF-8"?>

<phpunit ... >

   <testsuites>

       <testsuite name="Application Test Demo">

           <directory>./tests/</directory>

       </testsuite>

   </testsuites>

   ...

</phpunit>

Writing a Basic Unit Test

After completing the above mentioned processes successfully, you can now write the basic unit test case for your Laravel application by navigating to the tests/Feature/ExampleTest.php. Here, you can write test cases for testing fundamental features of the application.

<?php

namespace Tests\Feature;

use Tests\TestCase;

use Illuminate\Foundation\Testing\WithoutMiddleware;

use Illuminate\Foundation\Testing\DatabaseMigrations;

use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase

{

   /**

    * A basic test example.

    *

    * @return void

    */

   public function testBasicTest()

   {

       $response = $this->get('/');

       $response->assertStatus(200);

   }

}

You can use seven of the basic PHPUnit assertions to write tests for your Basket class. These assertions are:

  1. assertTrue()
  2. assertFalse()
  3. assertEquals()
  4. assertNull()
  5. assertContains()
  6. assertCount()
  7. assertEmpty()

assertTrue() and assertFalse()

The main function of assertTrue() and assertFalse() is that it allows you to assert and check either the values equates to true or false.

This makes it perfect for testing those methods which output result in Boolean values. As we have a method called has($item) defined in our Basket class, which gives true or false for specified items upon checking its availability in the basket.

<?php
use App\Basket;

class BasicTest extends TestCase
{
public function testHasItemInBasket()
{
$basket = new Basket(['item_one', 'item_two', 'item_three']);

$this->assertTrue($basket->has('item_one'));
$this->assertFalse($basket->has('item_four'));
}
}?>

If i run the ./vendor/bin/phpunit command now, you will notice the output includes:

OK (2 tests, 4 assertions)

assertEquals() and assertNull()

assertEquals() helps comparing actual value of the variable with the expected value. Within it, there is another function named takeOne(), which checks if the value of an item is currently in the basket or not. This method returns null value whenever the basket is empty. Besides it, we can also assertNull() which performs the same action.

In contrast with the assertTrue(), assertFalse(), and assertNull(), assertEquals() inputs two parameters. One is for the expected value while the other one for the actual value.

<?php
use App\Basket;

class BasicTest extends TestCase
{
public function testHasItemInBasket()
{
$basket = new Basket(['item_one', 'item_two', 'item_three']);

$this->assertTrue($basket->has('item_one'));

$this->assertFalse($basket->has('item_four'));
}

public function testTakeOneFromTheBasket()
{
$basket = new Basket(['item_three']);

$this->assertEquals('item_three'', $basket->takeOne());

// Null, now the basket is empty
$this->assertNull($basket->takeOne());
}
}

Run the phpunit command, and you should see:

OK (3 tests, 6 assertions)

Using assertSee()

To see whether your web page is displaying the right results or not, assertSee() is a great method to check its display and to assure its result for which it is intended to be.

Given, When, Then in Testing

If you want to test particular functions of your code, then you should follow the intrinsic pattern of Given, When and Then.

Given – It states the initial environment setup you would like to test. You can use some data, or can even setup a model factory in this step.

When – When refers to test specific function/method and called at some particular stage of the testing process.

Then – In this part, you declare about the result how it should look like.

Testing Laravel Application

Unit testing is not the only testing process, you will need for your application. Though it is necessary in most of the cases, and must be a compulsory part of your development process, it is not necessary that it will fulfill your all testing needs. Sometimes your application has complex views, navigation and forms, and you want testing of these components too.

You might also like: Laravel Dusk for Browser Testing

This is where Laravel’s built-in test helpers come into play and make testing of few components easy just as the Unit testing does.

Earlier in this Laravel unit testing example, we saw the default files within the /tests/ directory and left the ./tests/ExampleTest.php file to review at the later stage. So open it now, it should look like this:

<?php

class ExampleTest extends TestCase

{

   /**

* A basic functional test example.

*

* @return void

*/

   public function testBasicExample()

   {

       $this->visit('/')

            ->see('Laravel 5.5');

   }

}

As you can see, the test in this case is quite simple and easy to understand. Without having any additional or prior knowledge about how Laravel test helpers works, you can understand that it outputs some like this:

  • when I visit / (webroot)
  • I should see ‘Laravel 5

When you will open the application in your web browser, you will see a splash screen with “Laravel 5” written. After successfully passing test with PHPUnit, it is right to say that the output of this example test is spot-on.

This test ensures that the web page made at the / path, gives output with the text ‘Laravel 5’. Though it looks like a simple test and doesn’t seem much critical, but whenever your web app needs to display sensitive information, test like this can simply avert you from deploying broken application.

Token Mismatch Exception Error

Laravel 5 comes with a lot stunning new features. The framework has been developed with many advanced functionalities, such as the automatic enabling of CSRF protection on all default routes. This new advanced feature reduces your application’s vulnerability to CSRF attacks. But on the same time, also makes your all Unit tests to fail with TokenMismatchException.

Read More About: Laravel CSRF Protection

So if you want your unit tests to run accordingly and doesn’t want to modify it to include valid CSRF token. Then you just have to disable token validation process when running unit tests. Just add the following code to your app’s token verification middleware to disable token validation.

/**

* Override to disable validation when testing.

*

* @param \Illuminate\Http\Request $request

* @return bool

*/

protected function tokensMatch($request)

{

   // Don't validate CSRF when testing.

   if(env('APP_ENV') === 'laraveltesting') {

       return true;

   }

   return parent::tokensMatch($request);

}

Final Words

In this blog, I have briefly explained about Laravel unit testing using PHPUnit. The package is known for its optimized test cases. It ensures that each and every component of the application passes from the standard testing process and applications doesn’t go broken for deployment.

Also this article covers the usage of Laravel’s built-in test helpers, which signifies its own importance other than the PHPUnit. As at some points, these built-in test helpers gives convenience for testing some critical app components.

If you still have any questions regarding Unit testing in Laravel, or want to contribute your thoughts on this blog, you can write down your comments in the comments section below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Pardeep Kumar

Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. You can email him at pardeep.kumar@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!