Scroll to top
8 min read

Irrespective of the application you're dealing with, testing is an important and often overlooked aspect that you should give the attention it deserves. Today, we're going to discuss it in the context of the Laravel web framework.

In fact, Laravel already supports the PHPUnit testing framework in the core itself. PHPUnit is one of the most popular and widely accepted testing frameworks across the PHP community. It allows you to create both kinds of tests—unit and functional.

We'll start with a basic introduction to unit and functional testing. As we move on, we'll explore how to create unit and functional tests in Laravel. I assume that you're familiar with basics of the PHPUnit framework as we will explore it in the context of Laravel in this article.

Unit and Functional Tests

If you're already familiar with the PHPUnit framework, you should know that you can divide tests into two flavors—unit tests and functional tests.

In unit tests, you test the correctness of a given function or a method. More importantly, you test a single piece of your code's logic at a given time.

In your development, if you find that the method you've implemented contains more than one logical unit, you're better off splitting that into multiple methods so that each method holds a single logical and testable piece of code.

Let's have a quick look at an example that's an ideal case for unit testing.

1
public function getNameAttribute($value)
2
{
3
    return ucfirst($value);
4
}

As you can see, the method does one and only one thing. It uses the ucfirst function to convert a title into a title that starts with uppercase.

Whereas the unit test is used to test the correctness of a single logical unit of code, the functional test, on the other hand, allows you to test the correctness of a specific use case. More specifically, it allows you to simulate actions a user performs in an application in order to run a specific use case.

For example, you could implement a functional test case for some login functionality that may involve the following steps.

  • Create the GET request to access the login page.
  • Check if we are on the login page.
  • Generate the POST request to post data to the login page.
  • Check if the session was created successfully.

So that's how you're supposed to create the functional test case. From the next section onward, we'll create examples that demonstrate how to create unit and functional test cases in Laravel.

Setting Up the Prerequisites

Before we go ahead and create actual tests, we need to set up a couple of things that'll be used in our tests.

We will create the Post model and related migration to start with. Go ahead and run the following artisan command to create the Post model.

1
$php artisan make:model Post --migration

The above command should create the Post model class and an associated database migration as well.

The Post model class should look like:

1
<?php
2
// app/Post.php

3
namespace App;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class Post extends Model
8
{
9
    //

10
}

And the database migration file should be created at database/migrations/YYYY_MM_DD_HHMMSS_create_posts_table.php.

We also want to store the title of the post. Let's revise the code of the Post database migration file to look like the following.

1
<?php
2
3
use Illuminate\Support\Facades\Schema;
4
use Illuminate\Database\Schema\Blueprint;
5
use Illuminate\Database\Migrations\Migration;
6
7
class CreatePostsTable extends Migration
8
{
9
    /**

10
     * Run the migrations.

11
     *

12
     * @return void

13
     */
14
    public function up()
15
    {
16
        Schema::create('posts', function (Blueprint $table) {
17
            $table->increments('id');
18
            $table->string('name');
19
            $table->timestamps();
20
        });
21
    }
22
23
    /**

24
     * Reverse the migrations.

25
     *

26
     * @return void

27
     */
28
    public function down()
29
    {
30
        Schema::dropIfExists('posts');
31
    }
32
}

As you can see, we've added the $table->string('name') column to store the title of the post. Next, you just need to run the migrate command to actually create that table in the database.

1
$php artisan migrate

Also, let's replace the Post model with the following contents.

1
<?php
2
namespace App;
3
4
use Illuminate\Database\Eloquent\Model;
5
6
class Post extends Model
7
{
8
    /**

9
     * Get the post title.

10
     *

11
     * @param  string  $value

12
     * @return string

13
     */
14
    public function getNameAttribute($value)
15
    {
16
        return ucfirst($value);
17
    }
18
}

We've just added the accessor method, which modifies the title of the post, and that's exactly what we'll test in our unit test case. That's it as far as the Post model is concerned.

Next, we'll create a controller file at app/Http/Controllers/AccessorController.php. It'll be useful to us when we create the functional test case at a later stage.

1
<?php
2
// app/Http/Controllers/AccessorController.php

3
namespace App\Http\Controllers;
4
5
use App\Post;
6
use Illuminate\Http\Request;
7
use App\Http\Controllers\Controller;
8
9
10
class AccessorController extends Controller
11
{
12
    public function index(Request $request)
13
    {
14
        // get the post-id from request params

15
        $post_id = $request->get("id", 0);
16
        
17
        // load the requested post

18
        $post = Post::find($post_id);
19
        
20
        // check the name property

21
        return $post->name;
22
    }
23
}

In the index method, we retrieve the post id from the request parameters and try to load the post model object.

Let's add an associated route as well in the routes/web.php file.

1
Route::get('accessor/index', 'AccessorController@index');

And with that in place, you can run the http://your-laravel-site.com/accessor/index URL to see if it works as expected.

Unit Testing

In the previous section, we did the initial setup that's going to be useful to us in this and upcoming sections. In this section, we are going to create an example that demonstrates the concepts of unit testing in Laravel.

As always, Laravel provides an artisan command that allows you to create the base template class of the unit test case.

Run the following command to create the AccessorTest unit test case class. It's important to note that we're passing the --unit keyword that creates the unit test case, and it'll be placed under the tests/Unit directory.

1
$php artisan make:test AccessorTest --unit

And that should create the following class at tests/Unit/AccessorTest.php.

1
<?php
2
// tests/Unit/AccessorTest.php

3
namespace Tests\Unit;
4
5
use Tests\TestCase;
6
use Illuminate\Foundation\Testing\DatabaseMigrations;
7
use Illuminate\Foundation\Testing\DatabaseTransactions;
8
9
class AccessorTest extends TestCase
10
{
11
    /**

12
     * A basic test example.

13
     *

14
     * @return void

15
     */
16
    public function testExample()
17
    {
18
        $this->assertTrue(true);
19
    }
20
}

Let's replace it with some meaningful code.

1
<?php
2
// tests/Unit/AccessorTest.php

3
namespace Tests\Unit;
4
5
use Tests\TestCase;
6
use Illuminate\Foundation\Testing\DatabaseMigrations;
7
use Illuminate\Foundation\Testing\DatabaseTransactions;
8
use Illuminate\Support\Facades\DB;
9
use App\Post;
10
11
class AccessorTest extends TestCase
12
{
13
    /**

14
     * Test accessor method

15
     *

16
     * @return void

17
     */
18
    public function testAccessorTest()
19
    {
20
        // load post manually first

21
        $db_post = DB::select('select * from posts where id = 1');
22
        $db_post_title = ucfirst($db_post[0]->name);
23
        
24
        // load post using Eloquent

25
        $model_post = Post::find(1);
26
        $model_post_title = $model_post->name;
27
        
28
        $this->assertEquals($db_post_title, $model_post_title);
29
    }
30
}

As you can see, the code is exactly the same as it would have been in core PHP. We've just imported Laravel-specific dependencies that allow us to use the required APIs. In the testAccessorTest method, we're supposed to test the correctness of the getNameAttribute method of the Post model.

To do that, we've fetched an example post from the database and prepared the expected output in the $db_post_title variable. Next, we load the same post using the Eloquent model that executes the getNameAttribute method as well to prepare the post title. Finally, we use the assertEquals method to compare both variables as usual.

So that's how to prepare unit test cases in Laravel.

Functional Testing

In this section, we'll create the functional test case that tests the functionality of the controller that we created earlier.

Run the following command to create the AccessorTest functional test case class. As we're not using the --unit keyword, it'll be treated as a functional test case and placed under the tests/Feature directory.

1
$php artisan make:test AccessorTest

It'll create the following class at tests/Feature/AccessorTest.php.

1
<?php
2
// tests/Feature/AccessorTest.php

3
namespace Tests\Feature;
4
5
use Tests\TestCase;
6
use Illuminate\Foundation\Testing\WithoutMiddleware;
7
use Illuminate\Foundation\Testing\DatabaseMigrations;
8
use Illuminate\Foundation\Testing\DatabaseTransactions;
9
10
class AccessorTest extends TestCase
11
{
12
    /**

13
     * A basic test example.

14
     *

15
     * @return void

16
     */
17
    public function testExample()
18
    {
19
        $this->assertTrue(true);
20
    }
21
}

Let's replace it with the following code.

1
<?php
2
// tests/Feature/AccessorTest.php

3
namespace Tests\Feature;
4
5
use Tests\TestCase;
6
use Illuminate\Foundation\Testing\WithoutMiddleware;
7
use Illuminate\Foundation\Testing\DatabaseMigrations;
8
use Illuminate\Foundation\Testing\DatabaseTransactions;
9
use Illuminate\Support\Facades\DB;
10
11
class AccessorTest extends TestCase
12
{
13
    /**

14
     * A basic test example.

15
     *

16
     * @return void

17
     */
18
    public function testBasicTest()
19
    {
20
        // load post manually first

21
        $db_post = DB::select('select * from lvl_posts where id = 1');
22
        $db_post_title = ucfirst($db_post[0]->name);
23
24
        $response = $this->get('/accessor/index?id=1');
25
26
        $response->assertStatus(200);
27
        $response->assertSeeText($db_post_title);
28
    }
29
}

Again, the code should look familiar to those who have prior experience in functional testing.

Firstly, we're fetching an example post from the database and preparing the expected output in the $db_post_title variable. Following that, we try to simulate the /accessor/index?id=1 GET request and grab the response of that request in the $response variable.

Next, we've tried to match the response code in the $response variable with the expected response code. In our case, it should be 200 as we should get a valid response for our GET request. Further, the response should contain a title that starts with uppercase, and that's exactly what we're trying to match using the assertSeeText method.

And that's an example of the functional test case. Now, we have everything we could run our tests against. Let's go ahead and run the following command in the root of your application to run all tests.

1
$phpunit

That should run all tests in your application. You should see a standard PHPUnit output that displays the status of tests and assertions in your application.

And with that, we're at the end of this article.

Conclusion

Today, we explored the details of testing in Laravel, which already supports PHPUnit in its core. The article started with a basic introduction to unit and functional testing, and as we moved on we explored the specifics of testing in the context of Laravel.

In the process, we created a handful of examples that demonstrated how you could create unit and functional test cases using the artisan command.

If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Don't hesitate to express your thoughts using the feed below!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.