cspray / assert-throws
当测试抛出复杂异常的代码时,用于断言的PHPUnit。
0.1.0
2024-05-27 22:55 UTC
Requires
- php: ^8.2
- phpunit/phpunit: ^10.0 | ^11.0
README
提供了一种使用PHPUnit 10或11测试抛出异常的代码的替代方法。主要优点是可以访问抛出的异常进行进一步检查。这在你需要检查异常的详细信息,而这些信息在PHPUnit中无法预期时可能很有用。以下示例作为快速入门,更多详情请参阅下面的详细指南。
<?php declare(strict_types=1); use Cspray\AssertThrows\ThrowableAssert; use PHPUnit\Framework\TestCase; final class MyTest extends TestCase { public function testExceptionPreviousInstanceOf() : void { $throwable = ThrowableAssert::assertThrows( static fn() => throw new RuntimeException(previous: new BadMethodCallException()) ); self::assertInstanceOf(BadMethodCallException::class, $throwable->getPrevious()); } }
安装
Composer 是安装此包的唯一支持方法。
composer require --dev cspray/assert-throws
详细指南
PHPUnit 默认提供了一种测试预期异常的合理方式。对于大多数情况,PHPUnit 提供的方法应该是足够的。然而,在某些情况下,你可能需要以 PHPUnit 中未提供的方式测试抛出异常的代码。这种情况包括你想测试 先前 的异常,或者异常是否包含特定领域的信息。在这些情况下,这个库最为适用。
此库提供的所有断言都接受一个预期抛出异常的可调用对象。如果没有抛出异常,则会抛出 PHPUnit\Framework\ExpectationFailedException
,导致测试失败。否则,将返回抛出的异常以进行额外的断言。
在 Cspray\AssertThrows\ThrowableAssert
类上有以下静态方法可用
<?php use \Cspray\AssertThrows\ThrowableAssert; $throwable = ThrowableAssert::assertThrows(static fn() => throw new RuntimeException()); $throwable = ThrowableAssert::assertThrowsExceptionType( static fn() => throw new BadMethodCallException(), BadMethodCallException::class ); $throwable = ThrowableAssert::assertThrowsExceptionTypeWithMessage( static fn() => throw new RuntimeException('My exception message'), RuntimeException::class, 'My exception message' );
除了具有静态方法的 ThrowableAssert
类之外,还有一些全局函数可用
<?php use function Cspray\AssertThrows\assertThrows; use function Cspray\AssertThrows\assertThrowsExceptionType; use function Cspray\AssertThrows\assertThrowsExceptionTypeWithMessage; $throwable = assertThrows(static fn() => throw new RuntimeException()); $throwable = assertThrowsExceptionType( static fn() => throw new BadMethodCallException(), BadMethodCallException::class ); $throwable = assertThrowsExceptionTypeWithMessage( static fn() => throw new RuntimeException('My exception message'), RuntimeException::class, 'My exception message' );
以及一个可以在你的 PHPUnit\Framework\TestCase
实现中使用的特性
<?php use Cspray\AssertThrows\ThrowableAssertTestCaseMethods; use PHPUnit\Framework\TestCase; class MyTestCase extends TestCase { use ThrowableAssertTestCaseMethods; public function testAssertThrows() : void { $throwable = self::assertThrows(static fn() => new RuntimeException()); } public function testAssertThrowsExceptionType() : void { $throwable = self::assertThrowsExceptionType( static fn() => throw new BadMethodCallException(), BadMethodCallException::class ); } public function testAssertThrowsExceptionTypeWithMessage() : void { $throwable = self::assertThrowsExceptionTypeWithMessage( static fn() => throw new RuntimeException('My exception message'), RuntimeException::class, 'My exception message' ); } }
你使用哪种方法是个人偏好。最终,所有示例都利用了 ThrowableAssert
类中可用的静态方法。