LogoLogo
Frontend
  • Introduction
  • Getting started
  • About
  • Retrieving data
    • Introduction
    • Making a request
    • Property paths
    • Data providers
    • HTTP data provider
    • GraphQL data provider
    • Queries
    • GraphQL queries
    • Query Manager
    • Custom query classes
    • Bulk queries
  • Changing data
    • Introduction
    • Transforming and mapping data
    • Accessing properties
    • Transforming data
    • Available transformers
    • Mapping data
  • Advanced usage
    • Validation
    • Caching
    • Data History
    • Events
    • Testing API requests
Powered by GitBook
On this page
  • MockResponseFromFile
  • Parameters
  • Description
  • Usage

Was this helpful?

  1. Advanced usage

Testing API requests

PreviousEvents

Last updated 10 months ago

Was this helpful?

When testing HTTP requests you need to create mock responses based on what would actually be returned from a real HTTP request. Symfony's HTTPClient has support for .

You can also use theMockResponseFromFile class to generate a mock response easily from a file.

MockResponseFromFile

Allows you to load a mock request from file.

Parameters

  • $filename (string) File to load mock response from

Description

Body file is loaded from {$filename}

The optional info file is loaded from {$filename}.info.php and must contain the $info variable (array). By default mock responses return a 200 status code which you can change by setting the $info array.

Usage

The following code loads ./responses/api-test.json and if it exists ./responses/api-test.json.info.php to create a mock response.

use Symfony\Component\HttpClient\MockHttpClient;
use Strata\Data\Api_DELETE\RestApi;
use Strata\Data\Response\MockResponseFromFile;

$responses = [
    new MockResponseFromFile(__DIR__ . '/responses/api-test.json'),
];

$api = new RestApi('https://example.com/');
$api->setClient(new MockHttpClient($responses, 'https://example.com/'));

$response = $api->get('test');

// Outputs:404
echo $response->getStatusCode();

// Outputs: JSON response content
echo $response->getContent();

// Outputs: 0
echo $api->getHeader($response, 'X-Total-Results');

./responses/api-test.json

{
  "message": "PAGE NOT FOUND"
}

./responses/api-test.json.info.php

<?php
$info = [
    'http_code' => 404,
    'response_headers' => [
        'X-Total-Results' => '0'
    ]
];
  • http_code (int) - the last HTTP response code

  • response_headers (array) - an array of response headers

See for possible info, the most common are:

testing HTTP requests
ResponseInterface::getInfo()