How to Write Unit Test Case on Slim 3 to Test API | Devstringx

Back to Blog
UNIT TEST CASE ON SLIM 3

How to Write Unit Test Case on Slim 3 to Test API | Devstringx

Prerequisites :

-PHP 7.3

-Visual Studio Code

  1. Install slim via composer

//run this command on terminal composer require slim/slim:”3.*”

install slim via composer

2. Install PHPUnit

//run this command on terminal

composer require-dev PHPUnit/PHPUnit ^7

phpUnit

Now, PHPUnit is successfully installed you can see it in the demo/composer.json file and in the vendor folder.

3. Now we have to create a demo/phpunit.xml configuration file which is used to configure the PHPUnit

phpunit.xml

4. Now we have to create our demo/tests folder in our project.

demo/tests

5. Now create the demo/src folder inside the src folder you have to create a file name routes.php in which you will write your API.

routes.php

In the routes.php file, I have created an API for the addition of two numbers.

6. Now we have to set up the autoload to autoload everything from the tests directory in the composer.json file.

composer dump-autoload

Write “autoload-dev”: { “psr-4”: { “Tests\\”: “tests/” } } this in your composer.json file And run command-

composer dump-autoload –o

7. Now coming to the demo/tests folder inside the tests folder we have to create a Functional folder inside that I have created a BaseTestCase class which is extended from TestCase class.

App function

Inside BaseTestCase class , we have created runApp function passing the $requesMethod (POST,GET), $requestUri(api name),$requestData(array of data), inside this function I have created mock environment objects with custom information. Mock Environment objects are only useful when writing unit tests.after that I have setting up the $request = Request::createFromEnvironment($environment) object.Now adding the requested data if exist.now settingup the response object.create an object $app = new App();

After that process the application $response = $app->process($request, $response) And return the response.

8. Now create the file for testing out API demo/tests/Functional/routesApiTest

routesApiTest

In this we have created a class routesApiTest extended from BaseTestCase class If you are writing a test case then you always have to write test as a prefix of the function like testaddNum or you can write as I wrote in my case /** * @test */.now create a function addendum inside this function I have called runApp method in which I am passing the 3 parameters first-method which is post,second-API name,third-data array. Now I am using assertEquals methods in the first parameter is what I expect and the second parameter $response->getBody() what it returns.

9. Now run the command in terminal

./vendor/bin/PHPUnit tests

Share this post

Back to Blog

Hire A Resource