Unit testing is an important part of writing principled PHP programs. PHP has several testing frameworks available, but for this example, we'll use PHPUnit, which is one of the most popular.
For the sake of demonstration, this code is in a single file, but it could be split into separate files. Testing code typically lives in a separate directory from the code it tests.
```php
<?php
use PHPUnit\Framework\TestCase;
// We'll be testing this simple implementation of an
// integer minimum. Typically, the code we're testing
// would be in a source file named something like
// `IntUtils.php`, and the test file for it would then
// be named `IntUtilsTest.php`.
function intMin($a, $b) {
return ($a < $b) ? $a : $b;
}
// A test is created by writing a class that extends TestCase
// with methods beginning with 'test'.
class IntMinTest extends TestCase
{
public function testIntMinBasic()
{
$ans = intMin(2, -2);
// assertEquals will report test failures but continue
// executing the test. assertSame is used here as it's
// a strict comparison (===).
$this->assertSame(-2, $ans, "intMin(2, -2) = $ans; want -2");
}
// Writing tests can be repetitive, so it's common to use
// a data provider to supply test cases.
public function intMinProvider()
{
return [
[0, 1, 0],
[1, 0, 0],
[2, -2, -2],
[0, -1, -1],
[-1, 0, -1],
];
}
/**
* @dataProvider intMinProvider
*/
public function testIntMinTableDriven($a, $b, $want)
{
$ans = intMin($a, $b);
$this->assertSame($want, $ans, "got $ans, want $want");
}
}
// Benchmark tests in PHP are not as standardized as in some other languages.
// Here's a simple way to benchmark our function:
function benchmarkIntMin($iterations)
{
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
intMin(1, 2);
}
$end = microtime(true);
return ($end - $start) / $iterations;
}
// Usage:
$iterations = 1000000;
$avgTime = benchmarkIntMin($iterations);
echo "Average time per operation: " . ($avgTime * 1000000) . " microseconds\n";