A
A
Anton B.2021-02-24 09:08:01
PHP
Anton B., 2021-02-24 09:08:01

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


Such a test passes, I am confused by the fact that the output in the console is "not clean".
The result of the tests is green, but from the line with willThrowException messages get to the console.
Is it normal? Or am I not doing it right?

Tried on a simple example (without nested services) - with a separate class/method.
There you can remove Exception messages from the console
by adding to the test
$this->expectException(MyException::class);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2021-02-24
@SilenceOfWinter

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 question

Ask a Question

731 491 924 answers to any question