导航菜单

测试与调试

单元测试

  • 使用PHPUnit进行单元测试。
  • 编写测试用例和测试套件。
  • 使用数据提供器。
<?php
// 单元测试示例

// 1. 安装PHPUnit
// composer require --dev phpunit/phpunit

// 2. 测试类示例
class CalculatorTest extends PHPUnit\Framework\TestCase
{
    public function testAdd()
    {
        $calculator = new Calculator();
        $result = $calculator->add(1, 2);
        $this->assertEquals(3, $result);
    }

    /**
     * @dataProvider additionProvider
     */
    public function testAddWithDataProvider($a, $b, $expected)
    {
        $calculator = new Calculator();
        $result = $calculator->add($a, $b);
        $this->assertEquals($expected, $result);
    }

    public function additionProvider()
    {
        return [
            [0, 0, 0],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 2],
        ];
    }

    public function testException()
    {
        $calculator = new Calculator();
        $this->expectException(InvalidArgumentException::class);
        $calculator->divide(1, 0);
    }
}

// 3. 运行测试
// ./vendor/bin/phpunit tests/CalculatorTest.php
?>