Answer the question
In order to leave comments, you need to log in
PHPUnit Exception messages in the console - is it normal?
Good afternoon.
Tell me please.
The question arose on a specific example for Symfony, but it seems to be not tied to the framework.
In the test for the controller, I want to test the response for a situation where one of the internal services used by the controller throws an Exception. That is, for example, the service makes a request to an external API, but a situation has arisen when this API is not available.
In the test I do this:
$serviceStub = $this->createMock(ServiceInterface::class);
// имитируем, что someMethod не имеет доступа к внешнему API
$serviceStub->method('someMethod')->willThrowException(
new MyException(JsonResponse::HTTP_SERVICE_UNAVAILABLE, 'External API is not available.')
);
// подменяем сервис в контейнере
$this->client->getContainer()->set(self::SERVICE_ID, $serviceStub);
// далее запрос к контроллеру
$this->client->request(Request::METHOD_GET, self::CONTROLLER_ENDPOINT_URL);
// и далее asserts для response
$this->expectException(MyException::class);
Answer the question
In order to leave comments, you need to log in
expectException is not "remove from the console", you must specify its type when testing for exceptions.
class ExceptionTest extends TestCase
{
public function testException(): void
{
$this->expectException(InvalidArgumentException::class);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question