我有一个在提交表单时执行外部 API 调用的网页。我的想法是模拟HttpClientInterface
,只要一个完整的 E2E 场景需要一个正在运行的开发服务器来达到这个目的,这在我的情况下并不总是可行的。
这是我到目前为止所尝试的:
services.yaml
when@test:
services:
_defaults:
public: true
test.Symfony\Contracts\HttpClient\HttpClientInterface: '@Symfony\Contracts\HttpClient\HttpClientInterface'
我的测试场景:
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))
);
}
}
但它给了我以下错误:Symfony\Component\HttpClient\Exception\InvalidArgumentException: MockResponse instances must be issued by MockHttpClient before processing
. 显然它不适用于PantherTestCase
(尽管它适用于WebTestCase
测试)。
在集成测试期间是否可以以某种方式模拟响应?