Skip to content
Advertisement

How to mock the Symfony HttpClient as a dependecy?

I have a class into which I inject an instance of SymfonyComponentHttpClientHttpClient as a constructor parameter.

I’m looking at the documentation page at https://symfony.com/doc/current/components/http_client.html#testing-http-clients-and-responses where it is suggested to use $client = new MockHttpClient($responses); as a way to create a Mock client.

When I pass the mocked client to my class I get the error:

TypeError: Argument 3 passed to AppAllocatorStrategyAbstractStrategy::__construct() must be an instance of SymfonyComponentHttpClientHttpClient, instance of SymfonyComponentHttpClientMockHttpClient received.

How do I obtain a Mock that will satisfy the typing constraint and also allow me to mock up responses?

Advertisement

Answer

You shouldn’t depend on SymfonyComponentHttpClient, but on SymfonyContractsHttpClientHttpClientInterface.

MockHttpClient implements that interface, so it’s a valid substitution for injection in that case.

If you inject HttpClient, because you want to use the factory to create arbitrary clients at runtime, mocking is going to be harder. But it’s unlikely that’s what you really want.

The correct way to integrate the Http Client is by type-hinting for the interface, and letting the framework instantiate the appropriate client depending on your configuration.

That is cleaner (you are depending on an abstraction and not on a concretion), and so ii is much easier to write tests for.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement