⌘K
Noting Found

View all related articles

All You Need To Know To Start Using PHPUnit in Laravel Application

Laravel 4 mins read

Table of Content

    Introduction

    Laravel is built with testing in mind. In fact, support for testing with PHPUnit is included out of the box and a phpunit.xml file is already set up for your application. The framework also ships with convenient helper methods that allow you to expressively test your applications.

    Prerequisite

    You need to know the following:

    • Need to know PHP
    • Need to have a basic understanding of OOP
    • Basics of Laravel framework.
    • Basics of artisan commands

    What is Unit Testing

    a Unit Test, as the word describe, it let you test your application unit by unit. Meaning, with unit test you can split your logic in your app to small units and test them individually, imagine you have a login system in your app, and you want to test it. So, You can split the logic or, in other meaning, make the login system looks like small units like the following:

    • LoginTest
    • LoginWithSocialMediaTest
    • RegisterTest
    • ForgetPasswordTest
    • ResetPasswordTest
    • RememberMeTest

    And with this logic, you can test your code individually.

    What's TDD in Unit Testing

    The TDD meaning when you come to the unit testing world is in a simple word Writing Your Tests Before Writing Your Actual Code, and this approach has a really great pros.

    • Let you discover your code before writing it.
    • Let you write your application logic step by step.
    • Always wants to do before begin working in writing your code.
    • let you write the scenario of your application.

    Let me give you an example here. OK, you want to write a login system, and you don't know how to begin, you will write a test -we will know how later- and begin drawing ... for example you will decide the user go to URL /login by GET request, after that you will show him a login page by LoginIndexController ... and so on.

    After you done that you will run the test and see the errors. OH! Wait. There's no such thing called /login in my routes file. Not a big deal, let's create one, and you will run the test again and discover there's no such thing called LoginIndexController. No problem, let creates this also, and so on until your test get passes.

    Believe me, the first time it will be an annoying thing, but after time you will love the process and discover more things a long the way, and the important thing. Congrats, :smiley: You are a problem solver now!

    What is the Benefits From Testing The Code

    Imagine yourself developing a large system, and it has a lot of modules in it, and you decided after 6 months from now to add a feature or refactor your code. The Question is: How to make sure when you add this great feature or make a refactoring the application does not break!!

    You know what! When you begin writing tests and all passes, and you decide to refactor your code after 6 months from now. You will do it without any fair, because you know when you finish refactoring you will run your tests, and if there is any failure on them, you will discover immediately what's wrong and how to solve this problem before deploy the updates to production.

    Introduction To PHPUnit

    PHPUnit is a framework written by Sebastian Bergmann and it helps you write unit tests, and it provides a handful of methods ships with it. Also, Laravel ships with PHPUnit out of the box, which we'll discover in the next few lines.

    Difference Between Feature & Unit Testing

    I struggled a lot in the past to understand the difference between these two. But I'll simplify this for you.

    Feature Tests: simply the logic in your UI, meaning you will write test thinking of the end user, and you will ask questions like:

    • When the user hits /login what he will find?
    • If the user does not fill the password form, is the error required error appears or not?
    • When fill a form, what happens after?
    • When he/she authenticated, what can I do after?
    • When the user not authorized, which exception will throw?

    So, here you will think of the front of your application and try to build a logic fits your needs and your customers too.

    Unit Tests: simply, this works with the Database Layer, meaning you will write test thinking of the database and its records, and you will ask questions like:

    • If the user register, the number of users in the db increase?
    • Let's test the count of users after someone deletes his/her account.

    So, here you will find yourself to test the backend and the logic of your tables, nothing related to the user or to the frontend.

    Your First Test

    Enough talking and let's jump in to the bushiness

    Environment

    When running tests, Laravel will automatically set the configuration environment to testing because of the environment variables defined in the phpunit.xml file. Laravel also automatically configures the session and cache to the array driver while testing, meaning no session or cache data will be persisted while testing.

    You are free to define other testing environment configuration values as necessary. The testing environment variables may be configured in your application's phpunit.xml file, but make sure to clear your configuration cache using the config:clear Artisan command before running your tests!

    The .env.testing Environment File

    In addition, you may create a .env.testing file in the root of your project. This file will be used instead of the .env file when running PHPUnit tests or executing Artisan commands with the --env=testing option.

    Creating Tests

    To create a new test case, use the make:test Artisan command. By default, tests will be placed in the tests/Feature directory:

    1php artisan make:test UserTest

    If you would like to create a test within the tests/Unit directory, you may use the --unit option when executing the make:test command:

    1php artisan make:test UserTest --unit

    Once the test has been generated, you may define test methods as you normally would use PHPUnit. To run your tests, execute the vendor/bin/phpunit or php artisan test command from your terminal:

    1<?php
    2 
    3namespace Tests\Unit;
    4 
    5use PHPUnit\Framework\TestCase;
    6 
    7class ExampleTest extends TestCase
    8{
    9 /**
    10 * A basic test example.
    11 *
    12 * @return void
    13 */
    14 public function test_basic_test()
    15 {
    16 $this->assertTrue(true);
    17 }
    18}

    Running Tests

    As mentioned previously, once you've written tests, you may run them using phpunit:

    1./vendor/bin/phpunit

    In addition to the phpunit command, you may use the test Artisan command to run your tests. The Artisan test runner provides verbose test reports in order to ease development and debugging:

    1php artisan test

    Any arguments that can be passed to the phpunit command may also be passed to the Artisan test command:

    1php artisan test --testsuite=Feature --stop-on-failure

    Handful method when you test

    There are many handful methods you can use in the phpUnit and Here's the most used ones:

    1$this->assertEqual()
    2$this->assertInstanceOf()
    3$this->assertSessionHasErrors()
    4$this->assertRedirect()
    5$this->assertStatus()

    You can see the full list on PHPUnit documentation, and in the Laravel documentation.

    Conclusion

    Today We Learned about PHPUnit Framework and how to use it properly with your environment.

    If you have any questions, you can use comment them below, and I'll be more than happy to answer them.

    Hope you learned something useful today!

    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    We care about the protection of your data. Read our Privacy Policy.