插件窝 干货文章 高效测试异常:Codeception AssertThrows 的救星

高效测试异常:Codeception AssertThrows 的救星

Codeception expectException assertThrows 测试 282    来源:    2025-03-14

在软件开发中,异常处理是一个重要的部分,确保代码在遇到错误时能够优雅地处理。Codeception 是一个功能强大的 PHP 测试框架,它允许开发者编写单元测试、功能测试和验收测试。然而,Codeception 本身并没有直接提供 assertThrows 这样的方法来测试异常。不过,我们可以通过一些技巧来实现类似的功能。

使用 expectException 方法

PHPUnit 是 Codeception 的底层测试框架之一,它提供了 expectException 方法来测试代码是否抛出了预期的异常。你可以在 Codeception 的单元测试中使用这个方法。

public function testException()
{
    $this->expectException(\InvalidArgumentException::class);

    // 调用会抛出异常的代码
    $this->someMethodThatThrowsException();
}

自定义 assertThrows 方法

如果你希望在 Codeception 中更频繁地使用 assertThrows 这样的断言,你可以自定义一个辅助方法。以下是一个简单的实现:

trait AssertThrows
{
    public function assertThrows(callable $callback, string $expectedException): void
    {
        $thrown = false;

        try {
            $callback();
        } catch (\Throwable $exception) {
            if ($exception instanceof $expectedException) {
                $thrown = true;
            }
        }

        $this->assertTrue($thrown, "Expected exception $expectedException was not thrown.");
    }
}

你可以在你的测试类中使用这个 trait:

class MyTest extends \Codeception\Test\Unit
{
    use AssertThrows;

    public function testException()
    {
        $this->assertThrows(function () {
            $this->someMethodThatThrowsException();
        }, \InvalidArgumentException::class);
    }
}

使用 Codeception 的 expectException 模块

Codeception 还提供了一个 expectException 模块,可以在功能测试中使用。你需要在 codeception.yml 配置文件中启用这个模块:

modules:
    enabled:
        - \Helper\ExpectException

然后在测试中使用:

public function testException(FunctionalTester $I)
{
    $I->expectException(\InvalidArgumentException::class, function () {
        $this->someMethodThatThrowsException();
    });
}

总结

虽然 Codeception 本身没有直接提供 assertThrows 方法,但通过使用 PHPUnit 的 expectException 方法、自定义辅助方法或 Codeception 的 expectException 模块,你可以轻松地测试代码是否抛出了预期的异常。这些方法可以帮助你编写更健壮和可靠的测试用例。