Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the Symfony HttpClient as a dependecy?

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 of Symfony\Component\HttpClient\HttpClient, instance of Symfony\Component\HttpClient\MockHttpClient received.

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

like image 991
Andy Avatar asked Jan 26 '23 02:01

Andy


1 Answers

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.

like image 91
yivi Avatar answered Jan 28 '23 09:01

yivi