0
0
Laravelframework~30 mins

Unit tests in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Unit Tests in Laravel
📖 Scenario: You are building a simple Laravel application that manages a list of tasks. Each task has a title and a status indicating if it is completed or not.To keep your code reliable, you want to write unit tests that check if your Task model behaves correctly.
🎯 Goal: Create a unit test class for the Task model in Laravel. You will write tests to check if a task can be created with a title and if the default status is false (not completed).
📋 What You'll Learn
Create a Task model with title and completed attributes
Create a unit test class called TaskTest
Write a test method test_task_can_be_created_with_title that asserts a task's title is set correctly
Write a test method test_task_default_completed_is_false that asserts the default completed status is false
💡 Why This Matters
🌍 Real World
Unit tests help ensure your Laravel models work correctly and prevent bugs when you change code.
💼 Career
Writing unit tests is a key skill for Laravel developers to maintain code quality and reliability.
Progress0 / 4 steps
1
Create the Task model with attributes
Create a Laravel model class called Task in app/Models/Task.php with public properties title and completed. Set completed default to false.
Laravel
Need a hint?

Define a class Task that extends Model. Add public properties title and completed with default false.

2
Create the TaskTest unit test class
Create a unit test class called TaskTest in tests/Unit/TaskTest.php that extends Tests\TestCase. Add the use statement for the App\Models\Task model.
Laravel
Need a hint?

Create a class TaskTest that extends TestCase. Import the Task model with a use statement.

3
Write test for task creation with title
Inside the TaskTest class, write a public method called test_task_can_be_created_with_title. In it, create a new Task instance, set its title to 'Buy milk', and assert that the title property equals 'Buy milk' using $this->assertEquals().
Laravel
Need a hint?

Define a public method test_task_can_be_created_with_title. Create a Task object, set title, and assert equality with assertEquals.

4
Write test for default completed status
Add a public method called test_task_default_completed_is_false inside TaskTest. Create a new Task instance and assert that its completed property is false using $this->assertFalse().
Laravel
Need a hint?

Define a public method test_task_default_completed_is_false. Create a Task object and assert completed is false with assertFalse.