Knowledge Base

Testing API integrations with DUnitX and WebMock

To unit test if a Delphi application responds correctly to different reactions from an API it is possible to set up a test case via DUnitX and WebMock (https://getitnow.embarcadero.com/webmocks/) which simulates the API. Via WebMock, an endpoint can be called via an http client (for example from Indy or system.net). This can be done by adding the endpoint in the test procedure and giving the desired response. For example, in order to perform a GET request on the root of an API, the following ‘Stub’ can be created. This tells the WebMock to give the ‘NoContent’ status to a ‘GET’ request.

FWebMock
  .StubRequest('GET', '/')
  .ToRespond
  .WithStatus(NoContent);

 

The endpoint can then be called by retrieving the URL from the WebMock and passing it to the HTTP client:

URL := FWebMock.URLFor('/');
Response := FClient.Get(URL);

After this, the DUnitX test can be performed by checking the values in the response, for example by checking the status code of the response, in this case 204, NoContent:

Assert.AreEqual(204, Response.StatusCode);

In addition to specifying the status of the response, it is also possible to specify a body. This can be plain text, JSON, XML, etc. It is also possible to include a file name. In that case a file is sent along. Optionally, it is also possible to add a second parameter with the type of the body, in the case of JSON this is ‘application/json’. This value is passed in the headers with the response as ‘content-type’.

  FWebMock
    .StubRequest('GET', '/JSON')
    .ToRespond
    .WithStatus(OK)
    .WithBody('Hello');
  FWebMock
    .StubRequest('GET', '/JSON')
    .ToRespond
    .WithStatus(OK)
    .WithBody('{"Key": "Value"}', 'application/json');
  FWebMock
    .StubRequest('GET', '/JSON')
    .ToRespond
    .WithStatus(OK)
    .WithBody('C:/temp/test.txt');

Headers can also be added to the response. For example, to return the location of the created resource when creating a resource:

  FWebMock
    .StubRequest('POST', '/JSON')
    .ToRespond
    .WithStatus(Created)
    .WithHeader('location', 'http://example.com/resources/1');

Headers can also be created as TStrings objects and passed to the WebMock:

  Headers := TStringList.Create;
  Headers.Values['cache-control'] := 'no-cache';
  Headers.Values['last-modified'] := 'Sat, 13 Feb 2021 12:45:26 GMT';

  WebMock.StubRequest('GET', '/resources/1')
    .ToRespond
    .WithHeaders(Headers);

For a more detailed explanation, please visit: https://dev.to/rhatherall/series/3534

Written by Sibren van Ek
Delphi developer

Contact

Let us help you to realise your ambitions

GDK Software UK

(+44) 20 3355 4470

GDK Software USA

+1 (575) 733-5744