如何在phpunit中捕获异常
我正在进行一项功能测试,以检查特定用户是否无法更新资源,在这种情况下,API会重播404错误。这就是测试:如何在phpunit中捕获异常,php,symfony,phpunit,Php,Symfony,Phpunit,我正在进行一项功能测试,以检查特定用户是否无法更新资源,在这种情况下,API会重播404错误。这就是测试: static::createClient()->request( 'PUT', '/api/bookings/' . $bookingIdToUpdate, [ 'auth_bearer' => $token, 'json' => [ 'requ
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');
}
您确定在测试中引用了正确的类吗?尝试在ExpectExceptionies中引用Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class。我确信我引用的是正确的类。