例外

在 PHP 中測試行為時,您可能需要檢查是否已擲回例外或錯誤。若要建立預期會擲回例外的測試,您可以使用 throws() 方法。

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws(Exception::class);

如果您還想針對例外訊息進行宣告,您可以提供第二個參數給 throws() 方法。

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws(Exception::class, 'Something happened.');

如果例外類型不相關,而您只關注訊息,您可以只傳遞訊息而不指定例外的類型。

1it('throws exception', function () {
2 throw new Exception('Something happened.');
3})->throws('Something happened.');

您可以使用 throwsIf() 方法在給定的布林表達式評估為 true 時有條件地驗證例外。

1it('throws exception', function () {
2 //
3})->throwsIf(fn() => DB::getDriverName() === 'mysql', Exception::class, 'MySQL is not supported.');

就像 throwsIf() 方法一樣,您可以使用 throwsUnless() 方法在給定的布林表達式評估為 false 時有條件地驗證例外。

1it('throws exception', function () {
2 //
3})->throwsUnless(fn() => DB::getDriverName() === 'mysql', Exception::class, 'Only MySQL is supported.');

您也可以使用期望 API 的 toThrow() 方法驗證給定的閉包擲回一個或多個例外。

1it('throws exception', function () {
2 expect(fn() => throw new Exception('Something happened.'))->toThrow(Exception::class);
3});

如果您預期不會擲回任何例外,您可以使用 throwsNoExceptions() 方法。

1it('throws no exceptions', function () {
2 $result = 1 + 1;
3})->throwsNoExceptions();

有時,您可能只想將測試標記為失敗。您可以使用 fail() 方法來執行此操作。

1it('fail', function () {
2 $this->fail();
3});

您也可以為 fail() 方法提供訊息。

1it('fail', function () {
2 $this->fail('Something went wrong.');
3});

此外,您還可以驗證測試是否失敗,請使用 fails() 方法。

1it('fails', function () {
2 throw new Exception('Something happened.');
3})->fails();

就像 fail() 方法一樣,您也可以為 fails() 方法提供訊息。

1it('fails', function () {
2 throw new Exception('Something happened.');
3})->fails('Something went wrong.');

在了解如何撰寫宣告例外之測試後,下一步是探索「測試過濾」。這項功能讓您可以根據測試名稱、不乾淨檔案等條件,有效率地執行特定測試:過濾測試 →