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?