Here's a PHP class that calculates the factorial of a number along with a PHPUnit test:
Calculator.php:
<?php
class Calculator
{
/**
* Calculate the factorial of a non-negative integer
*
* @param int $number Non-negative integer
* @return int Factorial result
* @throws InvalidArgumentException If input is negative
*/
public function factorial(int $number): int
{
if ($number < 0) {
throw new InvalidArgumentException('Factorial is not defined for negative numbers');
}
$result = 1;
for ($i = 2; $i <= $number; $i++) {
$result *= $i;
}
return $result;
}
}
tests/CalculatorTest.php:
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
public function testFactorialWithPositiveNumbers()
{
$calculator = new Calculator();
$this->assertEquals(1, $calculator->factorial(0));
$this->assertEquals(1, $calculator->factorial(1));
$this->assertEquals(2, $calculator->factorial(2));
$this->assertEquals(6, $calculator->factorial(3));
$this->assertEquals(24, $calculator->factorial(4));
$this->assertEquals(120, $calculator->factorial(5));
}
public function testFactorialWithNegativeNumberThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Factorial is not defined for negative numbers');
$calculator = new Calculator();
$calculator->factorial(-1);
}
}
Explanation:
-
Calculator Class:
- The
factorial() method calculates the factorial of a non-negative integer
- Uses iterative approach (more efficient for large numbers than recursion)
- Throws
InvalidArgumentException for negative inputs
- Handles base case (0! = 1) automatically
-
Unit Tests:
testFactorialWithPositiveNumbers: Verifies correct calculations for various valid inputs
testFactorialWithNegativeNumberThrowsException: Tests exception handling for invalid input
To Run Tests:
- Install PHPUnit (using composer):
composer require --dev phpunit/phpunit
- Directory structure:
project/
├── src/
│ └── Calculator.php
├── tests/
│ └── CalculatorTest.php
└── composer.json
- Sample composer.json:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"require-dev": {
"phpunit/phpunit": "^9"
}
}
- Run tests:
./vendor/bin/phpunit tests
Example Output:
PHPUnit 9.5.27 by Sebastian Bergmann and contributors.
.. 2 / 2 (100%)
Time: 00:00.002, Memory: 4.00 MB
OK (2 tests, 7 assertions)
This implementation:
- Follows best practices for error handling
- Uses efficient iteration instead of recursion
- Includes comprehensive test cases
- Handles edge cases (0 and negative numbers)
- Follows PSR standards
- Includes proper type declarations
You can extend this class by adding more mathematical operations (fibonacci, prime checks, etc.) following the same test-driven approach.