Junior
Tell about unit tests.
sobes.tech AI
Answer from AI
Unit tests are automated tests that verify individual, minimal parts of code (modules, functions, classes) for correctness in isolation from the rest of the system.
Main advantages:
- Early detection of errors: Help identify problems during development.
- Improvement of code quality: Encourage writing more modular, testable, and understandable code.
- Speeding up development: Reduce manual testing time and facilitate refactoring.
- Documentation: Can serve as living documentation of code behavior.
Disadvantages:
- Require time to write: Writing tests takes additional time.
- Can be fragile: Changes in code may require adaptation of tests.
Main principles of writing unit tests (F.I.R.S.T. principle):
- Fast: Tests should run quickly.
- Independent: Each test should be independent of others.
- Repeatable: Running the test multiple times should yield the same result.
- Self-Validating: Tests should determine success or failure on their own.
- Timely: Tests should be written in a timely manner, ideally before writing the code.
Popular frameworks for unit testing in PHP:
- PHPUnit
- PestPHP
Example of a simple unit test using PHPUnit:
<?php
// tests/CalculatorTest.php
use PHPUnit\Framework\TestCase;
use App\Calculator; // Assuming there is a Calculator class
class CalculatorTest extends TestCase
{
public function testAdd()
{
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result); // Check that 2 + 3 equals 5
}
public function testSubtract()
{
$calculator = new Calculator();
$result = $calculator->subtract(5, 2);
$this->assertEquals(3, $result); // Check that 5 - 2 equals 3
}
}
<?php
// src/Calculator.php (example of the class being tested)
namespace App;
class Calculator
{
public function add(int $a, int $b): int
{
return $a + $b;
}
public function subtract(int $a, int $b): int
{
return $a - $b;
}
}