Issue Mocking External API in Functional Tests

I’m encountering an issue while attempting to mock an external API call within my functional test in Mautic Command. I aim to prevent the API call and use a mocked response instead. I’ve tried utilizing the MockHandler to avoid making the API request, but the endpoint is still being hit.

Initially, I attempted to mock the service by using:

$this->apiClient = $this->createMock(ApiClient::class);
self::$container->set('mautic.connection.apiclient', $this->apiClient);

However, this resulted in an error:

Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: The "mautic.connection.apiclient" service is already initialized, you cannot replace it.

To further address this, I tried the following approach:

$handlerStack = self::$container->get('mautic.http.client.mock_handler');
\assert($handlerStack instanceof MockHandler);
$handlerStack->append(
    function (RequestInterface $request) {
        Assert::assertSame('GET', $request->getMethod());
        Assert::assertSame('path/to.endpoint', $request->getUri()->__toString());

        return new Response(SymfonyResponse::HTTP_OK, [], 'Body string');
    }
);

Subsequently, I executed the command responsible for making the API call within the test:

$result = $this->testSymfonyCommand(SyncCommand::COMMAND_NAME);

However, despite these attempts, the command triggers the external API call rather than returning the mocked response.

I’d appreciate any insights or suggestions on effectively mocking the external API call within my command functional test to prevent hitting the endpoint.

Thank you in advance for your assistance!

Your command or whatever service is making the API calls must use this service to be able to use the MockHandler: