Creating & Running Tests with Laravel

Azraar Azward
3 min readAug 12, 2019

--

This article is for those who have not yet written tests but interested in writing test cases.

I will explain the flow of a simple test with some examples like how to write a very simple HTTP request test using laravel inbuilt features.

Environment: Laravel 5.8.x

  1. Simple HTTP response test

First of all, Let’s test the Laravel welcome screen.

Let’s check if its displayed correctly using a simple test case.

When you install Laravel, you already have a sample test case available at tests/Feature/ExampleTest.php.

<?php

namespace
Tests\Feature;

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

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

$response->assertStatus(200);
}
}

How can you create this manually? php artisan make:test ExampleTest

$response = $this->get(‘/’)

‘/’ is the url path, in this case its the default home page of laravel application. The $response->assertStatus(200) is to see if the response was success with a status code of 200.

Refer to the following for more status codes.

Run the following command in the Laravel root folder to execute this test case.

$ ./vendor/bin/phpunit ./tests/Feature/ExampleTest.php

Output should look like following,

2. View test

With the previous test we can’t test whether the Welcome screen is displayed and what contents it has.

Modify the code as following,

assertViewIs() to test what view was used in the method.

In addition we can use assertSeeUsing() method, which is to check if specified string is found in the welcome screen.

Test failing output

3. Test login
From here we will test screens with different results depending on whether the user is logged in or not.

Modify the code as following,

  • Using the first user record from database.
  • Creating a new user and using that for testing.

To avoid dummy user data getting cluttered in the database we can use DatabaseTransactions.

<?php

namespace
Tests\Feature;

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

class ExampleTest extends TestCase
{
/**
* A basic test example.
*
*
@return void
*/
public function testBasicTest()
{
$user = factory(User::class)->create();

$response = $this->actingAs($user)->get(route('home'));

$response->assertStatus(200)->assertViewIs('home')->assertSee('You are logged in!');
}
}

When this is used, the Database is rolled back after the test is executed, and the data created in the Database during the test execution will not remain.

Reference: https://laravel.com/docs/5.8/testing

--

--

Azraar Azward

An eager Software Engineer always loving to reach the impossible.