I have a web page that does an external API call when a form being submitted. My idea is to mock HttpClientInterface
as long as a complete E2E scenario will require a running dev server for that purpose, which is not always possible in my case.
Here is what I tried so far:
services.yaml
when@test:
services:
_defaults:
public: true
test.Symfony\Contracts\HttpClient\HttpClientInterface: '@Symfony\Contracts\HttpClient\HttpClientInterface'
My testing scenario:
class ClientAppointmentControllerTest extends PantherTestCase
{
public function testForm(): void
{
$client = static::createPantherClient();
$response = new MockResponse(null, ['http_code' => 400]);
$this->mockResponse($response);
$crawler = $client->request('GET', '/our-survey');
$form = $crawler->selectButton('Save')->form();
$client->submit($form);
static::assertEquals($response->getRequestMethod(), 'POST');
static::assertEquals($response->getRequestOptions()['body'], []);
static::assertEquals($response->getRequestUrl(), 'ad');
}
private function mockResponse(MockResponse $response): void
{
self::getContainer()->set(
'test.Symfony\Contracts\HttpClient\HttpClientInterface',
new TraceableHttpClient(new MockHttpClient($response))
);
}
}
But it gives me the following error: Symfony\Component\HttpClient\Exception\InvalidArgumentException: MockResponse instances must be issued by MockHttpClient before processing
. Apparently it does not work for PantherTestCase
(it works for WebTestCase
tests though).
Is it possible to mock response somehow during integration testing?
Probably this does answer your direct question about your HttpClientInterface mocking like you tried to do, but maybe show another way of approach for testing.
Example we have implementation:
We want to test
ImportantPage
controller, but we don't want to testImportantInformationService
service. So we ExtendImportantInformationService
service and Mock function response in newMockService..env.test
file:File structure should be like this:
So in general testing could look like this:
P.S. This is just WORKAROUND what worked for me to some extent. I'm sure there are better ways to do this. But SYMFONY container service mocking (like in WebTestCase) at the time of writing this, was not available in Panther tests, so I found other way to do it.