0
0
Laravelframework~5 mins

Unit tests in Laravel

Choose your learning style9 modes available
Introduction

Unit tests help check small parts of your code to make sure they work right. They catch mistakes early so your app stays reliable.

When you want to check if a function returns the correct result.
When you change code and want to make sure nothing else breaks.
When you build a new feature and want to test its parts separately.
When you want to avoid bugs before users find them.
When you want to write code that is easier to maintain and improve.
Syntax
Laravel
<?php

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_example()
    {
        $result = someFunction();
        $this->assertEquals(expectedValue, $result);
    }
}

Unit tests are classes that extend TestCase.

Test methods start with test and use assertions like assertEquals.

Examples
This test checks if 2 plus 3 equals 5.
Laravel
<?php

use Tests\TestCase;

class MathTest extends TestCase
{
    public function test_addition()
    {
        $sum = 2 + 3;
        $this->assertEquals(5, $sum);
    }
}
This test checks if the string contains the word 'Laravel'.
Laravel
<?php

use Tests\TestCase;

class StringTest extends TestCase
{
    public function test_string_contains()
    {
        $text = 'Hello Laravel';
        $this->assertStringContainsString('Laravel', $text);
    }
}
Sample Program

This unit test checks if multiplying 4 by 5 gives 20. It runs automatically when you run Laravel tests.

Laravel
<?php

namespace Tests\Unit;

use Tests\TestCase;

class CalculatorTest extends TestCase
{
    public function test_multiply()
    {
        $result = 4 * 5;
        $this->assertEquals(20, $result);
    }
}
OutputSuccess
Important Notes

Run tests with php artisan test in your terminal.

Keep tests small and focused on one thing.

Use descriptive test method names to know what they check.

Summary

Unit tests check small parts of code to catch errors early.

They use classes extending TestCase with assertion methods.

Run tests often to keep your app working well.