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
類別中可用的靜態方法。