Gabor
Gabor

Reputation: 155

How can I create a MockResponse with statusCode 400 header for MockHttpClient?

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:

Symfony\Component\HttpClient\Exception\ClientException : 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();
        }

Upvotes: 0

Views: 3863

Answers (3)

Thykof
Thykof

Reputation: 995

Here is what I do :

$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)
);

Upvotes: 2

Gabor
Gabor

Reputation: 155

I edited my question, but I realised that getContent() and toArray() throws ClientException, request() doesn't, so it cannot be caught

Upvotes: 0

Mohameth
Mohameth

Reputation: 376

So you're creating a function that returns an error 400 and then you when you call the function you always get a HTTP 400 error, am i right?

I don't understand what you want to achieve, can you please clarify?

Upvotes: 0

Related Questions