I would like to test different responses from an API using symfony/http-client, but how can I create statusCode 400?
This is what I tried:
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]); }
And use it like this:
$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());
Unfortunately I receive the following error:
SymfonyComponentHttpClientExceptionClientException : HTTP 400 returned for “https://api.someservice.net/api/”.
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(); }
Advertisement
Answer
I edited my question, but I realised that getContent() and toArray() throws ClientException, request() doesn’t, so it cannot be caught