Testing Lumen API With PHP Unit Tests
Mon, 11 Jun, 2018

Testing Lumen API With PHP Unit Tests

Earlier this year I started reading about TDD (Test Driven Development) approach and I began to see the importance of writing unit tests during software development. Good unit tests can help you document and define what you are supposed to do.

To know more about unit test and why it is important check out this thread on stackoverflow.

In this tutorial we are going to build a very simple RESTFul API with Lumen that can GET, POST, PUT and DELETE data from our database. Using our API endpoints, a user can create, view, edit and delete product from the database.

Here is the list of endpoints we are going to build.

    /products [GET] — gets all products.
    /products/id [GET] — gets just a product.
    /products [POST] — add a new product.
    /products/id [PUT] — edit existing product.
    /products/id [DELETE] — delete existing product.

We will make use of Fractal to structure our API response and use PHPUnit to test all our endpoints.

The focus of this tutorial is on how to use PHPUnit to test our endpoint. Our test will check the status code returned by our request and the structure of the response data.


Requirements

    Apache or nginx server
    At least PHP 5.4 release
    MYSQL Database
    Composer

    To get started on windows download WAMP, Mac OS — MAMP & Linux — LAMP

 

Setting Up The Development Environment

For the purpose of this tutorial we will be using Lumen 5.4 since it supports PHP 5.6 release. So if you are still using PHP 5.6 release we got you covered, but do well and upgrade to 7.0 or 7.1 release.

Open you terminal and run this command.
composer create-project laravel/lumen productAPI "5.4.*"

Change productAPI to any name of your choice.
Configure the .env File

The next thing you should do after installing Lumen is to rename .env.example file to .env and set your APP_KEY to a random string. Set DB_DATABASE to product_db, DB_USERNAME to your database username and DB_PASSWORD to your database password. Remember to create a database with the name product_db.

To avoid memcached error set CACHE_DRIVER and QUEUE_DRIVER to array

Our .env file should look like this
APP_ENV=local
APP_DEBUG=true
APP_KEY=afdfdhdfdueuekfhhfueyeyjcfh
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=product_db
DB_USERNAME=root
DB_PASSWORD=your_password

CACHE_DRIVER=array
QUEUE_DRIVER=array
Writing PHPUnit Test

Unit test helps us to define what we are supposed to do before we start doing it. Lumen has already configured our testing environment for us. The configuration file is phpunit.xml located inside the project directory. All our test will be inside the tests directory.

Create a new test file inside this directory. Name it ProductTest.php Our test file will extend the TestCase class. With this class we now have access to all methods we will use to test our endpoints.

Here is our test file

<?php
class ProductTest extends TestCase
{
    /**
     * /products [GET]
     */
    public function testShouldReturnAllProducts(){
        $this->get("products", []);
        $this->seeStatusCode(200);
        $this->seeJsonStructure([
            'data' => ['*' =>
                [
                    'product_name',
                    'product_description',
                    'created_at',
                    'updated_at',
                    'links'
                ]
            ],
            'meta' => [
                '*' => [
                    'total',
                    'count',
                    'per_page',
                    'current_page',
                    'total_pages',
                    'links',
                ]
            ]
        ]);
        
    }
    /**
     * /products/id [GET]
     */
    public function testShouldReturnProduct(){
        $this->get("products/2", []);
        $this->seeStatusCode(200);
        $this->seeJsonStructure(
            ['data' =>
                [
                    'product_name',
                    'product_description',
                    'created_at',
                    'updated_at',
                    'links'
                ]
            ]    
        );
        
    }
    /**
     * /products [POST]
     */
    public function testShouldCreateProduct(){
        $parameters = [
            'product_name' => 'Infinix',
            'product_description' => 'NOTE 4 5.7-Inch IPS LCD (3GB, 32GB ROM) Android 7.0 ',
        ];
        $this->post("products", $parameters, []);
        $this->seeStatusCode(200);
        $this->seeJsonStructure(
            ['data' =>
                [
                    'product_name',
                    'product_description',
                    'created_at',
                    'updated_at',
                    'links'
                ]
            ]    
        );
        

Stay Updated

Join the weekly Newsletter and never miss out on what's cooking at Devamplify