[英]How to catch an exception in phpunit
我正在進行功能測試以檢查特定用戶無法更新資源,在這種情況下,API 會以 404 錯誤重播。 這是測試:
static::createClient()->request(
'PUT',
'/api/bookings/' . $bookingIdToUpdate,
[
'auth_bearer' => $token,
'json' => [
'requestedBy' => 'a new value for this field',
],
]
);
self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND, 'This user is not expected to be able to update this booking');
當我運行這個測試時,我得到 404 響應,這很好:
Testing App\Tests\Integration\BookingTest
2020-01-21T15:00:07+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Not Found" at /var/www/html/vendor/api-platform/core/src/EventListener/ReadListener.php line 116
. 1 / 1 (100%)
Time: 38.89 seconds, Memory: 42.50 MB
OK (1 test, 1 assertion)
所以測試通過了,但控制台仍然顯示異常。 所以我在客戶端調用之前添加了這個:
$this->expectException(NotFoundHttpException::class);
這是結果:
Testing App\Tests\Integration\BookingTest
2020-01-21T15:15:05+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Not Found" at /var/www/html/vendor/api-platform/core/src/EventListener/ReadListener.php line 116
F 1 / 1 (100%)
Time: 41.39 seconds, Memory: 42.50 MB
There was 1 failure:
1) App\Tests\Integration\BookingTest::testUserCantUpdateABookingFromAnotherOrganisation
Failed asserting that exception of type "Symfony\Component\HttpKernel\Exception\NotFoundHttpException" is thrown.
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
正如你所看到的,異常被拋出,但同時我收到一個錯誤,說它不是。 知道如何抓住這個嗎?
確保首先調用以下方法:
$client->catchExceptions(false);
例如:
public function testUserCantUpdateABookingFromAnotherOrganisation()
{
$this->expectException(NotFoundHttpException::class);
$client = static::createClient();
$client->catchExceptions(false);
$client->request('GET', '/foo/bar');
$client->request(
'PUT',
'/api/bookings/' . $bookingIdToUpdate,
[
'auth_bearer' => $token,
'json' => [
'requestedBy' => 'a new value for this field',
],
]
);
self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND, 'This user is not expected to be able to update this booking');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.