Replace a private service in the Symfony container for testing

Is it possible to replace a private service in the DI container? I need to do this in my test environment, so that I can run integration tests but still mock HTTP calls to external APIs.

For example, I have this code that sets the mock for the HttpClientInterface:

$response = new MockResponse('"some json body"');
$client = new MockHttpClient([$response]);
self::$container->set(HttpClientInterface::class, $client);

// Execute controller / command and perform assertions
// ...

I have already tried to define the HttpClientInterface as a public service for my test environment with the config below, but this does not work as it isn’t instantiable (it’s an interface).

services:
  SymfonyContractsHttpClientHttpClientInterface:
    public: true

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *