Build a Laravel REST API with Test-Driven Development

Tram Ho

In this article, I will show you how to build a REST API application with Test-Driven Development using laravel framework.

What is Test-Driven Development?

TDD (Test Driven Development) is a software development method where programming, testing and design activities are intertwined.

Rules of TDD:

  1. Writing a unit test to describe one side of the program, the recently written test often fails because that feature is not yet installed.
  2. Write just enough code to pass the test
  3. Refactor the code until it meets the criteria of the simple code.
  4. Repeat the above operation

1. Install the project

Create a laravel project

composer create-project –prefer-dist laravel / laravel tdd-laravel.

Next, run 2 commands:

php artisan make: auth

and

php artisan migrate.

final initialization step we delete files ExampleTest.php in 2 directory tests/Unit and tests/Feature

2. Write code for the registration function

  1. Configuration in config/auth.php file

  1. Create routes in routes/api.php

  1. In the User.php model

  1. Create controller AuthController.php with the command

php artisan make: controller AuthController

In this step, we will add 2 methods (functions): authenticate () and register () methods. In the authenticate method, we authenticate the email and password. In the register method, we validate the input, create a new user with and create a token and then notify the user.

  1. To test what we’ve just written above, create the AuthTest class to test it

run the command

php artisan make: test AuthTest

Now, to check whether the above test results are correct, we use the command $vendor/bin/phpunit or $ phpunit . If the data case is not ideal then we need to look at the log and correct it.

Conclude

Through this article we can better understand the concept of TDD (Test-Driven Development) and the steps to implement TDD for a project using the Laravel Framework.

References

medium.com

Share the news now

Source : Viblo