I have a class into which I inject an instance of Symfony\Component\HttpClient\HttpClient
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
App\Allocator\Strategy\AbstractStrategy::__construct()
must be an instance ofSymfony\Component\HttpClient\HttpClient
, instance ofSymfony\Component\HttpClient\MockHttpClient
received.
How do I obtain a Mock that will satisfy the typing constraint and also allow me to mock up responses?
You shouldn't depend on Symfony\Component\HttpClient
, but on Symfony\Contracts\HttpClient\HttpClientInterface
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With