Check PHP behavior with boundary cases and strict value assertions.

Before starting: PHP classes and Composer.

Practice project: Extend the examples into a small PHPUnit study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. PHPUnit: test a threshold

    A test method in a TestCase subclass checks expected behavior. Strict assertions help distinguish values from merely similar representations.

    PHPUnit 12 with PHP 8.3+; save as tests/ScoreTest.php and run vendor/bin/phpunit tests/ScoreTest.php. For older PHP, select a supported PHPUnit release.

    <?php
    use PHPUnit\Framework\TestCase;
    final class ScoreTest extends TestCase {
        public function testBoundary(): void {
            $passed = fn(int $score): bool => $score >= 60;
            self::assertFalse($passed(59));
            self::assertTrue($passed(60));
        }
    }
    Check the output
    One test passes.

    Change >= to > and explain the failing assertion.

  2. PHPUnit: distinguish a number from a string

    assertSame compares both type and value. It can catch an accidental string where an integer result is required.

    PHPUnit 12 with PHP 8.3+; save as tests/ScoreTest.php and run vendor/bin/phpunit tests/ScoreTest.php. For older PHP, select a supported PHPUnit release.

    <?php
    use PHPUnit\Framework\TestCase;
    final class ScoreTest extends TestCase {
        public function testIntegerResult(): void {
            $result = 4 + 3;
            self::assertSame(7, $result);
        }
    }
    Check the output
    One test passes. Use this as a separate replacement example, not a second class with the same name.

    Replace $result with "7" and observe the type mismatch.

Open the PHPUnit learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.