bhylu.com

Advertisements

PHP Testing

A useful automated test checks an operation’s contract, including values that could reveal a boundary error. Successful compilation and one happy-path output are not enough.

How it works

Use deterministic fixtures and assertions whose failure actually fails the run. PHP assert can be disabled by runtime configuration, so these standalone contract checks throw explicitly. A maintained project should use an appropriate test runner through its build workflow. Separate pure unit tests from HTTP/database integration tests so each result says which boundary was exercised.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l tests.php
php tests.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · tests.php

<?php
declare(strict_types=1);

function checkedRemaining(int $stock,int $take): int {
    if ($stock<0 || $take<0 || $take>$stock) throw new InvalidArgumentException("Invalid counts");
    return $stock-$take;
}
if (checkedRemaining(5,5)!==0) throw new RuntimeException("Exact-fit test failed");
if (checkedRemaining(0,0)!==0) throw new RuntimeException("Empty-stock test failed");
try { checkedRemaining(2,3); throw new RuntimeException("Missing rejection"); }
catch (InvalidArgumentException $expected) {}
echo "Three contract checks passed\n";

Expected result

Three contract checks passed

The normal boundary, empty identity and invalid overdraw each have an explicit expected outcome. Throwing a different RuntimeException when rejection does not occur prevents a false green result. These are meaningful examples of a test strategy, not a full property-based proof or a benchmark.

Check the official PHP manual for detailed version and API contracts.