https://images.unsplash.com/photo-1617042375876-a13e36732a04?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw4NjkxNHwwfDF8c2VhcmNofDIxfHxjb2RlfGVufDB8MHx8fDE2MzQ5MjUwODQ&ixlib=rb-1.2.1&q=80&w=1080
Hey guys, last year I published Laravel API Test Helper, a Laravel package that can help you in developing and debugging your Laravel APIs. Since last year, 80% of my work has been around building APIs both at Across The Horizon Technologies and at Greenlite Nigeria. That’s why I have been putting out packages, which are code snippets that I end up duplicating across different projects.
In this tutorial, I will walk you through what the package is all about and how it can help speed up your API development with the Laravel framework.
Laravel Api Test Helper is a trait based Laravel package, meaning that it just contains a PHP trait that you can include in your test class, that’s all.
Let me show you 🙂
Installation & Setup
For this tutorial, I believe you have created a Laravel application . If you are new to Laravel, you can check out my Laravel Series for beginners.
First, let’s install the package with via composer:
composer require stephenjude/api-test-helper --dev
Next, we need you to include the helper trait inside our TestCase.php
. This class comes with every Laravel installation. You can find it inside the test
directory of your project.
<?php namespace Tests; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Stephenjude\ApiTestHelper\WithApiHelper; abstract class TestCase extends BaseTestCase { use CreatesApplication; use WithApiHelper; ... }
You can choose to include this trait to the particular test class that contains your API tests, but keeping it here makes it accessible to all our test class since they will extend the TestCase
abstract class.
Usage: Testing and Debugging APIs
For this tutorial, we will create a single endpoint that fetches all the users in our database. Let start by creating a test class for our user list endpoint.
php artisan make:test UserApiTest
This will create a test file inside the tests\Feature
directory in your Laravel project. This is the default for Laravel, but you can configure this directory to suit your project 🙂
PS: Make sure you have added your database credentials to your .env file.
Now let’s add the tests for our user list endpoint. We will use the Laravel getJson() to make a request to our endpoint and then set it to our test helper property $this->response
. This gives the Api Test Helper package access to the api response, with which the helper trait can help you test and debug the response.
<?php namespace Tests\Feature; use App\Models\User; use Tests\TestCase; class UserApiTest extends TestCase { public function test_get_user_list() { User::factory()->create(); $this->response = $this->getJson('api/users'); $this->dumpApiData(); } }
Dumping API Response: dumpApiData()
So I started out with the dumpApiData()
with allows us to dump the response returned from our response, this response can either be a valid response or an error response from the api or your application error itself.
Log API Response: logApiData()
You can also log the response of your api by calling the logApiData()
. This method logs all the response on your app to your log file.
... $this->response = $this->getJson('api/users'); $this->logApiData(); ...
Decoding API Response: decodeApiResponse()
You can also decode the API response by calling the decodeApiResponse() method which returns the response from your API.
PS: I will advice the use of the
json()
method provided in Laravel. I have already built this package before I learned about it.$this->response->json()
Testing Successful API Response
To test successful response, this package provides three(3) methods which I am going to explain with example.
To make a valid request, lets create a valid controller and route that can handle our request.
php artisan make:controller UserApiController -r
Here is our controller class with a valid response that returns list user.
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserApiController extends Controller { public function index() { return response()->json([ 'success' => true, 'data' => User::all(['id', 'name', 'email',]) ]); } ...
Now let’s add our user list route to api.php
Route::get('/users', [UserApiController::class, 'index']);
Now that we have a valid response for our endpoints, lets test the valid response methods.
assertApiSuccess()
... $this->response = $this->getJson('api/users'); $this->assertApiSuccess(); ...
The method asserts the response contains the success field with true value 'success' => true
or fails if it doesn’t.
assertApiResponse($data)
The method asserts the response contains the actual data or fails if it doesn’t.
... $user = User::factory()->create()->only(['id', 'name', 'email']); $this->response = $this->getJson('api/users/'.$user['id']); $this->assertApiResponse($user); ...
assertApiResponseCollection($data)
The method asserts the response contains the actual collection or fails if it doesn’t.
... User::factory()->count(2)->create(); $this->response = $this->getJson('api/users'); $this->assertApiResponseCollection(User::all(['id', 'name', 'email'])); ...
Conclusion
I believe you have learnt how to speed up your development process with this package and if you are new, you basically understand how to test your endpoints. You can find the link to the repository for this tutorial below and please don’t forget to star the package repository.
Laravel News Links