Kritim Yantra
Mar 27, 2025
Test-Driven Development (TDD) is a powerful approach to writing clean, maintainable, and bug-free code. In this blog, we'll explore how to use TDD in Laravel 12 with simple explanations and practical examples.
TDD stands for Test-Driven Development, which means:
This cycle is called "Red-Green-Refactor".
✅ Ensures code reliability
✅ Reduces bugs in production
✅ Makes refactoring easier
✅ Improves code design
First, install Laravel:
composer create-project laravel/laravel laravel-tdd-example
cd laravel-tdd-example
Laravel includes PHPUnit for testing. Check if tests run:
php artisan test
We want to create a task. Let's write a test first.
Create a test file:
php artisan make:test TaskTest
Now, write the test in tests/Feature/TaskTest.php
:
<?php
namespace Tests\Feature;
use Tests\TestCase;
class TaskTest extends TestCase
{
/** @test */
public function a_user_can_create_a_task()
{
// 1. Define the data
$taskData = ['title' => 'Learn TDD', 'description' => 'Write tests first!'];
// 2. Send a POST request to /tasks
$response = $this->post('/tasks', $taskData);
// 3. Assert that the task was created
$response->assertStatus(201);
$this->assertDatabaseHas('tasks', $taskData);
}
}
Run the test (it will fail - Red Phase):
php artisan test
php artisan make:migration create_tasks_table
Update the migration:
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
Run the migration:
php artisan migrate
php artisan make:model Task
In app/Models/Task.php
:
protected $fillable = ['title', 'description'];
php artisan make:controller TaskController --invokable
Add a route in routes/web.php
:
use App\Http\Controllers\TaskController;
Route::post('/tasks', TaskController::class);
In app/Http/Controllers/TaskController.php
:
public function __invoke(Request $request)
{
$task = Task::create($request->all());
return response()->json($task, 201);
}
Now, run the test again (Green Phase):
php artisan test
✅ Test passes!
Example:
php artisan make:request StoreTaskRequest
Update StoreTaskRequest
:
public function rules()
{
return [
'title' => 'required|string|max:255',
'description' => 'required|string',
];
}
Update the controller:
public function __invoke(StoreTaskRequest $request)
{
$task = Task::create($request->validated());
return response()->json($task, 201);
}
Run tests again to ensure they still pass.
Unit tests focus on small parts of code (e.g., a single method).
Example: Testing a Task
model method.
php artisan make:test TaskUnitTest --unit
tests/Unit/TaskUnitTest.php
:public function test_task_can_be_marked_as_completed()
{
$task = Task::factory()->create(['completed' => false]);
$task->markAsCompleted();
$this->assertTrue($task->completed);
}
Task
model:public function markAsCompleted()
{
$this->update(['completed' => true]);
}
php artisan test
TDD in Laravel 12 is simple:
This approach ensures high-quality, maintainable code.
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google