Unit Testing in Laravel with Sanctum
What's up my kids, I hope you are having a great time and having a great week, and even a better month. I wrote this post within thedevgang.com and I share it here so that it has more engagement with all of you. I hope you like it :3
It is already the last milestone of 2024 and other things, which are not worth talking about at this time. Well, in a previous blog post we migrated the Passport authentication library to Sanctum, however, now, I would like to delve into the unit tests of some endpoints and thus be able to execute them in a continuous integration pipeline such as Github Actions.
Previously, I had written about how to do unit tests with Passport in dev.to, this post can be found here, where I also explain what unit tests are and basic aspects about their implementation in Laravel. In this post, we will cover the following:
- Unit tests already with Sanctum implemented
- Testing some endpoints
Unit testing with Sanctum implemented
In the case of this post, I have some endpoints that I put together for an alternative project that I have been developing for a few months. This project has the following characteristics in terms of the framework and others:
- Laravel 11 with Sanctum 4
- PHPUnit 10
- Laravel Sail as a development environment
In this case we will test three endpoints that we set up for the authentication process of this app, first we will do the appropriate thing with the following method:
public function login(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', 'device_id' => 'required', ]); if ($validator->fails()) { return response()->json(['success' => false, 'error' => $validator->errors()], $this->badRequestStatus); } $result = $this->getToken(request('email'), request('password'), request('device_id')); if ($result['success'] == true) { return response()->json($result, $this->successStatus); } else { return response()->json(['success' => false, 'error' => 'Unauthorized'], $this->unauthorizedStatus); } }
This method is the one that completely manages the login process of our app, however the registration is not included in this snippet, that will be the next one to test. In this case, we have confirmed it and it seems to work correctly, but in order to make sure of this, we will set up their respective tests.
First with terminal enter this command:
php artisan make:test UserTest --unit
This will create a UserTest file in the tests/Unit folder, which will be completely “blank”, like the following:
<?php namespace Tests\Unit; use PHPUnit\Framework\TestCase; class ExampleTest extends TestCase { /** * A basic test example. */ public function test_basic_test(): void { $this->assertTrue(true); } }
Delete the test_basic_test() method, we won't need it. In this case I say that it is blank because it is only the mock of our unit tests and for this occasion it will be the one we use for the aforementioned methods. Now, before starting to schedule the tests, we need to make sure of the use cases that we will be executing and testing, therefore we have the following use cases to test:
- Login correct.
- Invalid login entering all data.
- Correct registration.
- Correct profile registration.
- Error profile registration due to not entering data.
- Profile not found.
- Registration of the correct profile and its feedback.
Once the use cases have been listed, we take into account that those that the aforementioned method covers in this case are cases 1 and 2, so we will proceed with them.
Test preparation
Now, before starting to code the tests, we need to configure them so that they can be executed correctly. To do this, we will create the setUp method within the UserTest file, which executes the instructions prior to executing the unit tests. This is where we can tell the system that it must carry out the migrations and be able to begin them if data is required, as well as the assignment of values in variables. The setUp method that we will create is structured like this:
public function setUp(): void { parent::setUp(); $this->faker = \Faker\Factory::create(); $this->name = $this->faker->name(); $this->password = 'password'; $this->email = 'valid@test.com'; $this->deviceId = $this->faker->uuid(); Artisan::call('migrate:fresh', ['-vvv' => true]); }
The setUp will do the following:
- Create an instance of Faker, a library to simulate data entry of various types of variables.
- We create a fictitious name
- We assign the password and email to default values.
- We assign a fictitious device ID also with the faker.
- Will run database migrations
Above this method, declare the global variables that we will use for all our tests:
public $faker; public $name; public $email; public $password; public $deviceId;
Development of unit tests
For test 1, we need to ensure that the login is correct by invoking the endpoint that we will call in our app. We will create the test_login_success method and it would look like this:
public function test_login_success() { Artisan::call('db:seed', ['-vvv' => true]); $body = [ 'email' => $this->email, 'password' => $this->password, 'device_id' => $this->deviceId ]; $this->json('POST', '/api/login', $body, ['Accept' => 'application/json']) ->assertStatus(200)->assertJson([ "success" => true ]); }
Este método, primeramente alimentará la base de datos con los catálogos pertinentes para poder confirmar que los mismos existen sin problemas. Después asignará el body y enviará los datos por medio de un request POST, al enviarlo, revisará que el status que devuelva su llamada es 200 y que los datos sean conforme al arreglo solicitado para confirmar, en este caso [ “success” => true ]. Si todo sale bien y se cumplen las condiciones, se considera prueba satisfactoria, en caso contrario, se considerará fallida y es donde se tendrá que revisar nuevamente el código.
Ahora bien, haremos el caso de uso 2. Para ello crea un método llamado test_login_error_with_data_ok e ingresa el siguiente código:
public function test_login_error_with_data_ok() { Artisan::call('db:seed', ['-vvv' => true]); $body = [ 'email' => 'invalid@test.com', 'password' => 'password', 'device_id' => $this->deviceId ]; $this->json('POST', '/api/login', $body) ->assertStatus(401)->assertJson([ "success" => false ]); }
A diferencia del anterior, en este caso, se le entregan datos erróneos y se solicita que confirme que el endpoint devuelva un error 401, así como un body [“success” => false ], esto con el fin de que se confirme que el sistema deniega el acceso a alguien que no tenga credenciales correctas.
Con esto, cubrimos el método presentado anteriormente y ya quedaría cubierto el método. Para poder probarlo, podemos ejecutar el siguiente comando bajo Sail:
docker compose exec laravel.test php artisan test
Te mostrará los siguientes resultados:
PASS Tests\Unit\UserTest ✓ login error with data ok 0.08s ✓ login success 0.16s
Si te sale todo bien como te lo he mostrado, tus unit tests han salido satisfactoriamente, pero estamos lejos de terminar. Ahora necesitamos probar el siguiente método:
public function register(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email|unique:users', 'password' => 'required', 'c_password' => 'required|same:password', 'device_id' => 'required', ]); if ($validator->fails()) { return response()->json(['success' => false, 'error' => $validator->errors()], $this->badRequestStatus); } $password = $request->password; $input = $request->all(); $input['password'] = bcrypt($password); $user = User::create($input); if (null !== $user) { $result = $this->getToken($user->email, $password, $request->device_id); if ($result['success'] == true) { return response()->json($result, $this->successStatus); } else { return response()->json(['success' => false, 'error' => 'Unauthorized'], $this->unauthorizedStatus); } } }
En este caso, realizaremos el caso de uso 3, el cual solicita confirmar que el registro sea correcto, para ello, crea el método test_register_success e ingresa el siguiente código:
public function test_register_success() { $body = [ 'name' => $this->name, 'email' => $this->email, 'password' => $this->password, 'c_password' => $this->password, 'device_id' => $this->deviceId ]; $this->json('POST', '/api/register', $body) ->assertStatus(200)->assertJson([ "success" => true ]); }
Al igual que con el login, solicitamos que nos confirme el sistema que se nos está entregando un código 200 así como el arreglo [“success” => true], si logramos eso, ya hemos terminado, pero si te das cuenta, nos hace falta la prueba en caso de que se equivoque el usuario. Ese método te lo dejo de tarea para que puedas corroborar tus conocimientos.
Ahora bien probaremos los siguientes métodos:
public function profile() { $user = Auth::user(); $profile = Profile::find($user->id); if (null !== $profile) { return response()->json(["success" => true, "data" => $user], $this->successStatus); } else { return response()->json(['success' => false, 'message' => 'Usuario no encontrado.'], $this->notFoundStatus); } }
public function createProfile(Request $request) { try { $validator = Validator::make($request->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'birth_date' => 'required|date', 'bloodtype' => 'required|numeric', 'phone' => 'required', 'gender' => 'required|numeric', 'country' => 'required|numeric', 'state' => 'required|numeric', ]); if ($validator->fails()) { return response()->json(['success' => false, 'error' => $validator->errors()], $this->badRequestStatus); } $user = Auth::user(); $profile = Profile::where(['user_id' => $user->id])->first(); $data = [ 'user_id' => $user->id, ]; $dataInsert = array_merge($data, $request->all()); if (null !== $profile) { $profile = $profile->update($dataInsert); } else { $profile = Profile::create($dataInsert); } return response()->json(["success" => true, "message" => 'Perfil actualizado correctamente.'], $this->successStatus); } catch (QueryException $e) { return response()->json(["success" => false, "message" => 'Error al actualizar el perfil.'], $this->internalServerErrorStatus); } }
Este par de métodos son los referentes a la gestión del perfil del usuario y su retroalimentación, por lo que los casos de uso que debemos probar son del 4 al 7. Para el caso 4, debemos crear un nuevo método llamado test_register_profile_success y agregamos el siguiente código:
public function test_register_profile_success() { $body = [ 'first_name' => $this->faker->firstName, 'last_name' => $this->faker->lastName, 'birth_date' => '1987-10-10', 'bloodtype' => 1, 'phone' => $this->faker->phoneNumber, 'gender' => 1, 'country' => 1, 'state' => 1, ]; $user = User::factory()->create(); $token = $user->createToken('TestToken')->plainTextToken; $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $token, ])->post('/api/user/profile', $body); $response->assertStatus(200); }
En esta ocasión, necesitamos declarar un arreglo que simule el contenido del cuerpo del request para que pueda ser enviado correctamente por el endpoint y una vez enviado, el confirmar que el request tiene una respuesta satisfactoria (200).
Para el caso del perfil erróneo por no ingresar datos, necesitamos agregar un nuevo método que denominaremos test_register_profile_validation_failed, el cual implementaremos de la siguiente forma:
public function test_register_profile_validation_failed() { $user = User::factory()->create(); $token = $user->createToken('TestToken')->plainTextToken; $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $token, ])->post('/api/user/profile', []); $response->assertStatus(400); }
En este caso, es prácticamente el mismo contenido de la prueba anterior, con la diferencia que ahora le enviamos un arreglo en blanco, para poder asegurarnos que si no se están enviando los datos correctamente, no permita la creación del perfil del usuario por medio de un Bad Request error (400).
El siguiente método probará que en caso de no encontrar el perfil de algún usuario, así lo indique con un código 404, por lo que creamos otro método denominado test_obtain_profile_not_found e ingresando el siguiente código.
public function test_obtain_profile_not_found() { $user = User::factory()->create(); $token = $user->createToken('TestToken')->plainTextToken; $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $token, ])->get('/api/user/profile'); $response->assertStatus(404); }
En el modelo de negocio, nosotros al registrarnos, creamos el usuario, mas no el perfil que tiene que ser ingresado posteriormente, por lo que al momento de ejecutar la prueba unitaria, al ejecutar el request para obtener el perfil, nos enviará un código 404, comportamiento que estamos buscando para esta prueba unitaria.
Finalmente para el último caso de uso, crearemos el método test_register_profile_and_obtain para confirmar que un mismo test pueda obtener dos comportamientos en un mismo flujo. Para este caso implementaremos el siguiente código:
public function test_register_profile_and_obtain() { $body = [ 'first_name' => $this->faker->firstName, 'last_name' => $this->faker->lastName, 'birth_date' => '1987-10-10', 'bloodtype' => 1, 'phone' => $this->faker->phoneNumber, 'gender' => 1, 'country' => 1, 'state' => 1, ]; $user = User::factory()->create(); $token = $user->createToken('TestToken')->plainTextToken; $this->withHeaders([ 'Authorization' => 'Bearer ' . $token, ])->post('/api/user/profile', $body); $response = $this->withHeaders([ 'Authorization' => 'Bearer ' . $token, ])->get('/api/user/profile'); $response->assertStatus(200); }
En este test, implementamos dos casos de uso realizados previamente, el primero es la creación del perfil y posteriormente, retroalimentamos el perfil, indicando a PHPUnit que deseamos confirmar que el response del endpoint que retroalimenta el perfil sea satisfactoria (código 200). Igualmente podríamos realizar el assert de la inserción de datos cambiando algunas líneas de código, pero por el momento es más que suficiente.
Ya terminando las pruebas unitarias, procedemos a ejecutar el comando docker compose exec laravel.test php artisan test y confirmamos el estatus de nuestras pruebas unitarias. Si nos salen de esta forma:
PASS Tests\Unit\UserTest ✓ login error with data ok. 0.10s ✓ login success. 0.15s ✓ register success. 0.20s ✓ register profile success. 0.10s ✓ register profile validation failed. 0.09s ✓ obtain profile not found. 0.10s ✓ register profile and obtain. 0.10s
Las pruebas unitarias salieron satisfactorias. En caso contrario, checa lo siguiente:
- The method that has had problems, check that it is not a code situation.
- Check that the PHPUnit configuration is appropriate, we will delve into it in the next post.
Likewise, I am going to explain how to configure Github Actions to run unit tests on it and even be able to obtain code coverage reports and a possible continuous deployment. I hope that this post, although long, serves to give you more context about unit testing and about a continuous integration and deployment process.
Happy coding!
The above is the detailed content of Unit Testing in Laravel with Sanctum. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
