技術情報
- 2023年11月28日
- 技術情報
Writing User CRUD API Feature Test in Laravel
Laravel empowers developers to build efficient and robust APIs effortlessly. Feature testing is an indispensable aspect of ensuring the reliability and functionality of our APIs, especially when it involves user CRUD operations. In this blog post, we’ll take a step-by-step journey through the code to feature test a User CRUD API in Laravel.
Step 1: Setting Up the Test Environment
Create a test class file with the following command.
php artisan make:test UserCrudApiTest
The test class file created can be found at tests/Feature/UserCrudApiTest.php
and codes are as follows.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class UserCrudApiTest extends TestCase
{
/**
* A basic feature test example.
*
* @return void
*/
public function test_example()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
Step 2: Define and modify the Test Class
Import necessary classes and traits. And remove default test_example method.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use App\Models\User;
class UserCrudApiTest extends TestCase
{
use RefreshDatabase;
}
The `UserCrudApiTest` class is declared, extending `TestCase` and using `RefreshDatabase` for database isolation.
`RefreshDatabase` ensures a clean database state for each test, and `TestCase` is the base test case class. `User` is imported to create and interact with user models.
Step 3: Testing User Creation
public function test_user_can_be_created()
{
$userData = [
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password123'),
];
$response = $this->json('POST', '/api/users', $userData);
$response->assertStatus(201)
->assertJson([
'name' => 'John Doe',
'email' => 'john@example.com',
]);
$this->assertDatabaseHas('users', [
'name' => 'John Doe',
'email' => 'john@example.com',
]);
}
This method tests the creation of a user. The `$this->json(‘POST’, ‘/api/users’, $userData)` line sends a POST request to create a user with the specified data. Assertions ensure a successful response, correct JSON structure, and that the user is stored in the database.
Step 4: Testing User Retrieval
public function test_user_can_be_retrieved()
{
$user = factory(User::class)->create();
$response = $this->json('GET', "/api/users/{$user->id}");
$response->assertStatus(200)
->assertJson([
'name' => $user->name,
'email' => $user->email,
]);
}
This method tests the retrieval of a user. A user is created using the factory, and a GET request is made to fetch the user’s details. Assertions verify a successful response and the correctness of the returned data.
Step 5: Testing User Update
public function test_user_can_be_updated()
{
$user = factory(User::class)->create();
$updateData = [
'name' => 'Updated Name',
'email' => 'updated.email@example.com',
];
$response = $this->json('PUT', "/api/users/{$user->id}", $updateData);
$response->assertStatus(200)
->assertJson($updateData);
$this->assertDatabaseHas('users', [
'id' => $user->id,
'name' => 'Updated Name',
'email' => 'updated.email@example.com',
]);
}
This method tests updating a user’s details. A user is created, and a PUT request updates the user’s data. Assertions check for a successful response, the correctness of the returned JSON, and the updated data in the database.
Step 6: Testing User Deletion
public function test_user_can_be_deleted()
{
$user = factory(User::class)->create();
$response = $this->json('DELETE', "/api/users/{$user->id}");
$response->assertStatus(204);
$this->assertDatabaseMissing('users', ['id' => $user->id]);
}
This method tests the deletion of a user. A user is created, and a DELETE request is made to delete the user. Assertions ensure a successful response and confirm that the user is no longer present in the database.
After writing the necessary test methods, we can test with the following artisan command.
php artisan test --filter UserCrudApiTest
This command uses the --filter
option to specify a particular test class, in this case, UserCrudApiTest
. Only the tests within the UserCrudApiTest
class will be executed.
The --filter
option can also be used to run specific methods within a test class. For example:
php artisan test --filter UserCrudApiTest::test_user_can_be_created
Also php artisan test
can be used to run all the tests in the application (all test files under tests
dir).
Conclusion
Feature testing User CRUD operations in a Laravel API provides confidence in the functionality and reliability of the endpoints. Each step, from setup to testing each CRUD operation, contributes to a robust testing suite that helps maintain a high standard of code quality in our Laravel applications.
Hope you enjoy that.
Asahi
waithaw at 2023年11月28日 10:00:00
- 2023年11月21日
- 技術情報
Getting Started with Unit Testing in Laravel
Unit testing is a crucial aspect of any robust software development process. In Laravel, a popular PHP framework, writing unit tests is not only easy but also highly encouraged. In this tutorial, we will go through the basics of writing unit tests in Laravel, ensuring the reliability and stability of the individual code units.
Prerequisites
Before diving into writing unit tests, make sure the following prerequisites be installed:
1. Composer
2. Laravel Installed
3. PHPUnit
Setting Up a Laravel Project
Use the following commands to set up a new project:
composer create-project --prefer-dist laravel/laravel my-laravel-app
cd my-laravel-app
Creating a Unit Test
Laravel provides a convenient Artisan command to generate a test class. Let’s create a simple unit test for a hypothetical `Calculator` class:
php artisan make:test CalculatorTest --unit
This will generate a test file located at `tests/Unit/CalculatorTest.php`. Open the file and you’ll see a basic test structure.
Writing a Unit Test
Now, let’s write a unit test for a basic addition method in our `Calculator` class. Open `CalculatorTest.php` and modify it as follows:
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\Calculator;
class CalculatorTest extends TestCase
{
public function testAddition()
{
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result);
}
}
In this example, assume we have a `Calculator` class in the `app` directory with an `add` method like that.
namespace App;
class Calculator
{
public function add($a, $b)
{
return $a + $b;
}
}
Running Unit Tests
To run the unit tests, use the following command:
php artisan test
This will execute all the tests in the `tests` directory.
Assertions
Laravel provides a variety of assertions that can be used in the tests. In this example, we used `assertEquals` to verify that the addition method returns the expected result. Explore other assertions and details in the official documentation https://laravel.com/docs/10.x/testing.
Conclusion
We’ve just written a first unit test in Laravel. As the application grows, writing tests for individual code units will become an integral part of the development process, ensuring that the code remains maintainable and reliable. Hope you enjoy that.
Asahi
waithaw at 2023年11月21日 10:00:00
- 2023年11月14日
- 技術情報
MongoDB Takes Control of Laravel Integration: Official Support Announced
MongoDB is now officially in charge of the Laravel framework’s community-driven MongoDB integration! This signals a commitment to regular updates, enhancing functionality, fixing bugs, and ensuring compatibility with the latest releases of both Laravel and MongoDB.

Formerly recognized as jenssegers/laravel-mongodb, this library expands Eloquent, Laravel’s ORM, providing PHP developers working with MongoDB a seamless experience through Eloquent models, query builders, and transactions.
For those eager to integrate MongoDB with the Laravel framework, explore the most recent release of this library, which introduces support for Laravel 10 – Laravel MongoDB 4.0.0. If you’re embarking on MongoDB PHP projects, a tutorial on constructing a Laravel + MongoDB back-end service and comprehensive library documentation are readily available here.
By Asahi
waithaw at 2023年11月14日 10:00:00
- 2023年10月17日
- 技術情報
Microsoft Phasing Out NTLM in Favor of Kerberos for Enhanced Authentication and Security in Windows 11
Microsoft has revealed its plan to phase out NT LAN Manager (NTLM) authentication in Windows 11 to enhance security and focus on bolstering the Kerberos authentication protocol. This move includes the introduction of features like Initial and Pass Through Authentication Using Kerberos (IAKerb) and a local Key Distribution Center (KDC) for Kerberos in Windows 11.

NTLM, a security protocol from the 1990s, was originally designed for user authentication, integrity, and confidentiality. However, it has been replaced by Kerberos since Windows 2000, though it continues to be used as a fallback option. NTLM relies on a three-way handshake for user authentication and uses password hashing, while Kerberos employs a two-part process with encryption.
NTLM has been found to have inherent security weaknesses and is vulnerable to relay attacks, which could potentially allow unauthorized access to network resources.
Microsoft is actively working to address hard-coded NTLM instances in its components as part of its preparation to disable NTLM in Windows 11. These changes will be enabled by default, with no need for additional configuration in most scenarios. NTLM will still be available as a fallback for maintaining compatibility with existing systems.
Asahi
waithaw at 2023年10月17日 10:00:00
Free Alternatives to GPT-4
Today, I would like to share about 3 free alternatives to GPT-4. Let’s take a look.
LlaMA 2
LlaMA 2 is a cutting-edge open-source large language model developed by Meta AI. It’s available for commercial use and comes with pre-trained models, fine-tuned models, and code resources. You can find all these assets on HuggingFace. You can also get a feel for how well the model performs by trying it out on HuggingChat. By making LlaMA 2 openly accessible, Meta AI is empowering researchers and developers to create innovative applications that leverage advanced language capabilities.
PaLM 2
Google AI’s PaLM 2 is Google’s latest large language model, excelling in advanced reasoning tasks like coding, mathematics, classification, question answering, translation, multilingual proficiency, and natural language generation. It surpasses previous state-of-the-art large language models like the original PaLM due to its optimized compute-scaling approach, improved dataset mixture, and architectural enhancements. You can access PaLM 2 for free using Bard. While there’s still room for improvement compared to GPT-4 in terms of quality and performance, it offers impressive capabilities.
Claude 2
Claude 2 represents the latest version of Anthropic’s conversational AI assistant. It offers improved performance, longer responses, and can be accessed through an API as well as a new public beta website, claude.ai. Developers at Anthropic have focused on enhancing its capabilities in areas such as coding, mathematics, and logical reasoning compared to earlier Claude versions. For instance, Claude 2 recently achieved a score of 76.5% on the multiple-choice section of the Bar exam, a significant improvement from Claude 1.3’s 73.0%. You can access various Claude models on Poe and experience their performance firsthand.
Conclusion
Despite GPT-4 being unavailable to the public, there are other promising open-source large language models emerging as alternatives that are accessible to everyone. While these models may not be as massive as GPT-4, they show that cutting-edge language AI is evolving rapidly and becoming more widely available. These freely accessible models excel in fields such as mathematics, coding, and logical reasoning, making them suitable replacements for various applications.
Asahi
waithaw at 2023年10月03日 10:00:00