Here's a simple PHP class that performs a basic calculation, along with a PHPUnit unit test to verify its behavior.
We'll create a class called Calculator which will have a method to add two numbers. Then we’ll write a corresponding PHPUnit test to ensure the method works correctly.
📁 Project Structure
code Copy code
/your-project/
├── Calculator.php
└── tests/
└── CalculatorTest.php
1. Calculator.php (Class File)
php Copy code
<?php
class Calculator
{
public function add(int|float $a, int|float $b): int|float
{
return $a + $b;
}
}
2. CalculatorTest.php (PHPUnit Test File)
Make sure you have PHPUnit installed . You can install it via PHAR or Composer.
php Copy code
<?php
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../Calculator.php';
class CalculatorTest extends TestCase
{
private Calculator $calculator;
protected function setUp(): void
{
$this->calculator = new Calculator();
}
public function testAddReturnsSumOfTwoNumbers(): void
{
$result = $this->calculator->add(2, 3);
$this->assertEquals(5, $result);
}
public function testAddHandlesNegativeNumbers(): void
{
$result = $this->calculator->add(-1, -2);
$this->assertEquals(-3, $result);
}
public function testAddHandlesFloats(): void
{
$result = $this->calculator->add(1.5, 2.5);
$this->assertEquals(4.0, $result);
}
}
✅ How to Run the Test
If you're using PHPUnit via PHAR:
bash Copy code
phpunit tests/CalculatorTest.php
Or if you’re using Composer:
bash Copy code
./vendor/bin/phpunit tests/CalculatorTest.php
✅ Expected Output
You should see something like:
code Copy code
PHPUnit ... by Sebastian Bergmann and contributors.
... 3 / 3 (100%)
Time: 00:00.006, Memory: 6.00 MB
OK (3 tests, 3 assertions)
Let me know if you want more complex operations (like subtract, multiply, divide) or error handling added!