Guide "How to mock clients in tests" #177
@bropp @ggagosh there are a lot of methods how to mock client. Each method is better in special cases. Could you please provide more details on your requirements from your projects and I will try to provide more information. Probably based on these answers we will be able to create documentation page.
Hi, first of all, thank you for your lib. I'd like to know if there is a example of how to do the mock. I replaced the handler, it's the MockHandler, but I can't add any request to the queue in the tests. I tried the
Could somebody help me with this, please? Thnx in advance
Well, I think I found a way through. One thing that I didn't mention before it was that I'm using api-platform and because I'm using api-platform, I'm using its ApiTestCase to write the functional tests, and the problem was that my modifications weren't being applied in the container. But, if I disable the kernel reboot (
static::createClient()->disableReboot(); $cli = static::createClient()->getContainer()->get('eight_points_guzzle.client.<client_name>'); $handlerStack = $cli->getConfig('handler'); $handlerStackRefl = new \ReflectionClass($handlerStack); $handler = $handlerStackRefl->getProperty('handler'); $handler->setAccessible(true); $mock = $handler->getValue($handlerStack);
After that, you can
$mock->append(new Response(200, , ''));
Api plataform uses SF4, so I just set the MockHandler in the
# config/services_test.yaml eight_points_guzzle: clients: <client_name>: handler: 'GuzzleHttp\Handler\MockHandler'
All that set, you're good to go. I hope it helps ^^
Coming back to this topic after a while, and a lot more use case experience, I'm no longer convinced the MockHandler was been the best way to implement the mocking mechanism.
When using Behat testing, the MockHandler that you fill up with MockResponses is not taken into account once the actual code is called.
All this leads me to believe going towards a middleware based mocking mechanism might be the best way to handle this problem (although I'm definitely not a fan of a record / replay system, this is so far the most usable I found)
Also it might be the opportunity to revisit the discussion we had way back about setting up a base interface for middlewares (#232):
@gregurco WDYT ?