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.
Jump into concepts and practice - no test required
Unit tests help check small parts of your code to make sure they work right. They catch mistakes early so your app stays reliable.
<?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.
<?php use Tests\TestCase; class MathTest extends TestCase { public function test_addition() { $sum = 2 + 3; $this->assertEquals(5, $sum); } }
<?php use Tests\TestCase; class StringTest extends TestCase { public function test_string_contains() { $text = 'Hello Laravel'; $this->assertStringContainsString('Laravel', $text); } }
This unit test checks if multiplying 4 by 5 gives 20. It runs automatically when you run Laravel tests.
<?php namespace Tests\Unit; use Tests\TestCase; class CalculatorTest extends TestCase { public function test_multiply() { $result = 4 * 5; $this->assertEquals(20, $result); } }
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.
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.
public function testSum() {
$a = 2;
$b = 3;
$this->assertEquals(5, $a + $b);
}public function testUserName() {
$user = new User();
$user->name = 'Alice';
$this->assertEquals('Alice', $user->username);
}