assert throws
0.1.0
提供另一种方法来测试使用 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 中不可用的方式测试异常抛出代码。此类示例包括您想要测试先前异常或异常是否包含域特定信息的代码。在这些情况下,这个库是最合适的。
该库提供的所有断言都采用一个预计会引发异常的可调用函数。如果没有抛出异常,将抛出PHPUnitFrameworkExpectationFailedException
从而导致测试失败。否则,将返回抛出的异常以进行其他断言。
CsprayAssertThrowsThrowableAssert
类提供以下静态方法:
<?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 '
);
以及在PHPUnitFrameworkTestCase
实现中使用的特征:
<?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
类中可用的静态方法。