我想使用 symfony/http-client 测试来自 API 的不同响应,但是如何创建 statusCode 400?
这是我尝试过的:
public static function mockShipmentResponseFail(): MockResponse
{
$body = [
'HttpStatusCode' => 400,
'HttpStatusDescription' => 'Bad Request',
'Message' => 'One or more shipments are invalid',
'Errors' => [
'Message' => 'The first line of the address must be 35 characters or less.',
'Cause' => 'DestinationAddressLine1',
'ErrorCode' => 'E1433', //Invalid field
'ErrorId' => '932478fg83r7gf'
]
];
return new MockResponse([json_encode($body)], ['http_code' => 400]);
}
并像这样使用它:
$responses = [CourierServiceTest::mockLoginResponse(), CourierServiceTest::mockShipmentResponseFail()];
$mockClient = new MockHttpClient($responses);
$someService = new SomeService($mockClient, $request->server);
$apiResponse = $someService->orders($tmpOrder1->getId());
$responseArray = json_decode($apiResponse->getContent(), true);
$this->assertEquals(400, $apiResponse->getStatusCode());
$this->assertJson($apiResponse->getContent());
不幸的是,我收到以下错误:
Symfony\Component\HttpClient\Exception\ClientException :为“https://api.someservice.net/api/”返回 HTTP 400。
try {
$apiResponse = $this->client->request('POST', $url, [
'headers' => [
'accept' => 'application/json',
'content-type' => 'application/json',
other headers
],
'body' => [
$body
]
]);
} catch (ClientException $exception) {
return $exception->getResponse();
}