Testing in Laravel

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.

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.

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

The Post model class should look like:

Powered by WPeMatico

Leave a Comment

Scroll to Top