Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    6. Уроки Node.js. Util и Наследование

    Programming

    15. Уроки Node.js. Асинхронная разработка. Введение.

    Wiki

    Роль Менеджера Продуктов

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / PHP / Laravel / Testing Laravel Applications Like a Pro with PHPUnit
    Laravel

    Testing Laravel Applications Like a Pro with PHPUnit

    Oluwaseun RaphaelBy Oluwaseun RaphaelDecember 4, 2020Updated:July 13, 2024No Comments9 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Testing Laravel Applications Like a Pro with PHPUnit
    Testing Laravel Applications Like a Pro with PHPUnit
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Testing Laravel Applications Like a Pro with PHPUnit
    Testing Laravel Applications Like a Pro with PHPUnit

    Introduction

    Test-Driven Development (TDD) is an approach to software development that utilizes a test-first environment where you write tests before writing proper code to fulfill the test and then refactoring. It’s a way to think through what your application is required or designed to do before you write code to build out the functionalities. This article is an introduction to testing Laravel Applications using PHPUnit, the most popular testing framework designed for PHP developers. This tutorial shows you why test-driven development is important in day to day activities as well as how to get started with writing tests in a Laravel application using PHPUnit,

    Why you should write tests for your application

    Testing is necessary because we all are bound to make mistakes. Some of these mistakes made in development carry no heavy consequences while some tend to be very costly or dangerous if neglected. The advantages of Test Driven Development poses are numerous, here are a few reasons why it is necessary to implement Test-driven development.

    • TDD helps avoid errors and bugs when introducing new features in an application
    • Project processes are made easier to track in a test-driven environment
    • TDD helps ease the process of documenting software
    • TDD inspires confidence when writing code
    • Bugs are easier to spot and fix in an environment where tests are written.

    Prerequisites

    This tutorial assumes you have the following:

    • Intermediate knowledge of Laravel and web development in general
    • A Laravel compatible development environment with Composer installed.

    Introducing PHPUnit

    PHPUnit is a developer-focused framework for testing applications built with PHP and its numerous frameworks. PHPUnit is built following the xUnit architecture for unit testing frameworks.

    Laravel is built with testing in mind and as a result, PHPUnit is a testing utility included by default in a fresh installation of Laravel so there is no need to go through so much of a hassle in setting up a testing environment. All you need to do is ensure the default values (which are usually good to go) are modified to your taste. For example, you might need to have a different database driver for your testing needs.

    Getting Started

    Our demo Laravel app will be a simple tasks manager API that will allow users to create tasks and delete them as necessary. To get started, create and navigate to a new Laravel project using composer by running:

    composer create-project laravel-testing-app
    cd laravel-testing-app

    Configuring a Testing Database

    When testing, it is very handy to have a testing database setup as you do not want to run tests against your actual database, and as a result, we will be making use of an in-memory SQLite database that keeps things simple and fast.

    To configure SQLite as your testing database, open up the phpunit.xml file and uncomment the following lines of code from the file

      ...
    
     <server name="DB_CONNECTION" value="sqlite"/> 
     <server name="DB_DATABASE" value=":memory:"/>
    
      ...

    Running Tests

    To run tests using PHP unit in your Laravel Application, navigate to your projects root directory and run either the /vendor/bin/phpunit command or the php artisan test command. Alternatively, you can create a custom alias (composer test) by adding "test": "vendor/bin/phpunit" to the scripts object in your project’s composer.json file as demonstrated in the code block below.

          ... 
    "scripts": {
            "post-autoload-dump": [
                "IlluminateFoundationComposerScripts::postAutoloadDump",
                "@php artisan package:discover --ansi"
            ],
            "test": "vendor/bin/phpunit",
            "post-root-package-install": [
                "@php -r "file_exists('.env') || copy('.env.example', '.env');""
            ],
            "post-create-project-cmd": [
                "@php artisan key:generate --ansi"
            ]
        }
    
         ...

    When you run the initial tests pre-written by Laravel using the php artisan test or composer test command, you get something similar to the screenshot below:

    Read More:  Development With LAMP Stack Illustrated Address Book Project
    The default Laravel tests pass
    The default Laravel tests pass

    The output above tells us that the two default tests: one unit & one feature test ran and passed successfully.

    Let’s dissect any of the ExampleTest.php files in the units Proceed to delete the ExampleTest.php files in both the Feature and Unit directories in our tests folder as we will create our own tests shortly.

    As explained above, our demo-project is a simple tasks manager app with the following requirements:

    • A /api/tasks/create route that accepts a POST request to create tasks
    • A /api/task{id}/complete endpoint that marks a given task as complete
    • A final /api/task/{id}/delete endpoint that deletes the given task from the database

    Now that we have our requirements clear let’s proceed to write tests accordingly that ensure our API does just that!

    Create a test file named EndpointsTest.php  by running:

    php artisan make:test InsertionTest

    Inside this file, delete the content of the default testBasicTest() method and add the following method instead.

    public function test_that_a_task_can_be_added()
        {
            $this->withoutExceptionHandling();
            $response = $this->post('/api/tasks/create', [
                'name' => 'Write Article',
                'description' => 'Write and publish an article'
            ]);
            $response->assertStatus(201);
            $this->assertTrue(count(Task::all()) > 1);
        }

    Let’s run through what the code above does:

    $this->withoutExceptionHandling() tells PHPUnit not to handle exceptions that we may get. This is to disable Laravel’s exception handling to prevent Laravel from handling exceptions that occur instead of throwing it, we do this so we can get a more detailed error reporting in our test output.

    $this->post('/task/create', []) makes a POST request to the task/create endpoint with the values given in the array.

    $response->assertStatus(201) instructs PHPUnit to confirm that the HTTP status code returned from the post request is a 201 i.e resource created.

    Next, we use the $this->assertTrue() method to confirm that the task was really saved in the database.

    On running the tests with php artisan test, we get the following feedback as our tests fail as expected.

    We get a 404 not found exception
    We get a 404 not found exception

    The tests result (with exception-handling disabled) tells us that our tests fail because a POST request sent to http://localhost/task/create threw a NotFoundException as the route could not be found.

    Let’s fix that by registering the route in our project’s web.php file.

    ...
    Route::group(['prefix' => 'tasks'], function () {
        Route::get('/{task}','TaskController@show');
        Route::post('/create', 'TaskController@create_task');
        Route::patch('{task}/complete', 'TaskController@mark_task_as_completed');
        Route::delete('/{id}', 'TaskController@destroy');
    });
     ...

    On running the tests further, we get the following error that tells us that the Task model/class inline 24 could not be found. This is because we have not created the class yet.

    All tests pass successfully now
    All tests pass successfully now

    Let’s create the Task class and its corresponding migration, factories and controllers by running php artisan make:model Task -a and then importing the created class by adding ” use AppModelsTask; ” at the top of our InsertionTest.php file.

    On running the tests once more, we get a result saying the tasks table could not be found which is expected because we do not have migrations created and run.

    Let’s create the table and run our migrations by adding the following migration to the public function up() method in the  create_tasks_table migration file.

     public function up()
        {
            Schema::create('tasks', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->text('description');
                $table->boolean('completed')->default(0);
                $table->timestamps();
            });
        }

    Next, modify your Models/Task.php file to allow the name, description, and status fields to become mass assignable by adding them to the fillable array as such:

           ...
    
    class Task extends Model
    {
           ...
        protected $fillable = ['name', 'description', 'status'];
    
        
    }
           ...

    On running the tests we have written so far, you should see them failing as expected

    Read More:  Top 6 Features of PHP 7.4 - Explained with Examples

    Test that a Task can be deleted

    In order to test if a task can be deleted, we will create some dummy tasks and attempt to delete them from the database. We can create dummy tasks using laravel factories as seen below.

    // TaskFactory.php 
    public function definition()
        {
            return [
                'name' => $this->faker->sentence(4),
                'description' => $this->faker->sentence(20),
                'completed' => random_int(0, 1)
            ];
        }

    Our test should look like this

        public function test_that_a_task_can_be_deleted()
        {
            $this->withoutExceptionHandling();
            Task::factory()->times(5)->create(); // create 5 tasks using the factory setup above
            $id_to_be_deleted = random_int(1, 5); // select a random task
            $this->delete("/api/tasks/$id_to_be_deleted/"); // send a request to delete it
            $this->assertDatabaseMissing('tasks', ['id' => $id_to_be_deleted]); // assert that the task deleted previouly does not exist in the database anymore.
        }

    As expected, the test fails. Let’s write the corresponding code to pass the test

    // TaskController.php 
    public function destroy($task)
        {
            $task_to_be_deleted = Task::findOrFail($task);
            $task_to_be_deleted->delete();
            return response()->json([
                'message' => 'task deleted successfully'
            ], 410);
        }

    Testing that a Task can be marked as completed

    In order to test that tasks can be marked as completed, we need to create a test task and then make a PATCH request to the endpoint responsible for that.

    public function test_that_a_task_can_be_completed(){
      $this->withoutExceptionHandling();
      $task_id = Task::create([
            'name' => 'Example Name',
            'description' => 'Demo dscription'
      ])->id; // create a task and store the id in the $task_id variable
      $response = $this->patch("/api/tasks/$task_id/complete"); //sends a patch request in order to complete the created task
      $this->assertTrue(Task::findOrFail($task_id)->is_completed() == 1); // assert that the task is now marked as completed in the database
      $response->assertJson([
                'message' => 'task successfully marked as updated'
      ], true); // ensure that the JSON response recieved contains the message specified
      $response->assertStatus(200); // furthe ensures that a 200 response code is recieved from the patch request
    }
    
    

    As expected, our tests fail, add the following methods to the Task model so our model is able to mark tasks as completed.

    / App/Models/Task.php 
          ...
       public function mark_task_as_completed()
        {
            $this->completed = 1;
            $this->save();
        }
        public function is_completed()
        {
            return $this->completed;
        }
    
          ...
    

    Lastly, add the corresponding code in the controller:

    // App/Http/Controllers/TaskController.php
        ...
    public function mark_task_as_completed(Task $task)
        {
            $task->mark_task_as_completed(); //calls the mark_task_as_complete method we created in the App/Models/Task.php file
            return response()->json([
                'message' => 'task successfully marked as updated'
            ], 200); //send a json response with the 200 status code
        }
    }
        ...

    When we run our tests now, we should get them all passing as expected. If an update is made to the codebase, tests should be written and run to ensure our application is still intact.

    Further Reading:

    We sure have covered a lot in this walkthrough. We got started by getting our project up and running using composer. Then, we configured PHPUnit to use a local SQLIte file for database related tests. Finally, we wrote our own test to make sure our API would work the way we expected.

    While we covered a lot, this is just the tip of the PHPUnit iceberg. To continue learning about testing Laravel application, I recommend that you check out Jeffery Way’s Testing Laravel course on Laracasts. Another wonderful resource is the Laravel testing docs.

    If you’d like to learn more about using PHPUnit, feel free to check out the official docs as well as a cheat-sheet of common PHPUnit utilities and functions here.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Oluwaseun Raphael

      Related Posts

      Building a WordPress Website with React (Frontity)

      December 21, 2020

      Development With LAMP Stack Illustrated Address Book Project

      July 22, 2020

      Top 6 Features of PHP 7.4 – Explained with Examples

      February 3, 2020
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      JavaScript September 14, 2018

      Fortune 500 top hiring trends in 2019. How top companies attract best talents?

      Nowadays while the competition for the top talents is becoming increasingly intense, it is important for the companies of any size and industry to develop an integrated recruitment strategy with an action plan. Fortune 500 companies in 2019 will continue to use AI- and computer-based algorithms in the process of job candidates search, recruitment marketing, better employment brand building and remote workforce.

      Mastering B2B Lead Generation: A Complete Guide for Success

      November 28, 2024

      Node.js Lesson 8: Inheritance from Errors, Error

      October 28, 2020

      Why You Should Use APIs To Build Your Own Price Tracking Engine

      January 15, 2020

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      5 Website Security Threats and How to Counter Them

      Beginners October 16, 2019

      Introduction to Micro Frontends: The New Tech on the Block

      JavaScript June 27, 2019

      Unlocking Organizational Growth: The Crucial Role of Recruitment

      Recruitment December 5, 2024

      Top 10 Vue.js Interview Questions

      JavaScript February 9, 2019

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Interview

      15 Common JavaScript Questions

      Programming

      Crafting Interactive User Interfaces Using JavaScript Techniques

      Angular

      How to Create a Personal Blogging Website: Front-End (Angular) #2

      Most Popular

      How to Prepare for Your First Coding Job Interview?

      Interview

      Mastering Common Interview Questions: Strategic Responses Guide

      Interview

      Уроки Express.js. Основы и Middleware. Часть 2.

      Programming
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.