0

我想使用 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();
        }
4

3 回答 3

0

因此,您正在创建一个返回错误 400 的函数,然后当您调用该函数时,您总是会收到 HTTP 400 错误,对吗?

我不明白你想要实现什么,你能澄清一下吗?

于 2020-10-15T15:14:31.020 回答
0

我编辑了我的问题,但我意识到 getContent() 和 toArray() 会抛出 ClientException,request() 不会,因此无法捕获

于 2020-10-19T05:44:28.757 回答
0

这是我所做的:

$body = '{"data": 1}';

// create the mock response
$client = new MockHttpClient([new MockResponse(
    $body,
    [
        'response_headers' => ['content-type' => 'application/json'],
        'http_code' => 400
    ]
)]);

// do the request
$response = $client->request('GET', $url);

// assert the content 
$this->assertEquals(
    $body,
    $response->toArray(false)
);
于 2021-07-16T09:28:52.883 回答