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.
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.
Apache or nginx server
At least PHP 5.4 release
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
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
Join the weekly Newsletter and never miss out on what's cooking at Devamplify