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.
The endpoint can then be called by retrieving the URL from the WebMock and passing it to the HTTP client:
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:
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’.
Headers can also be added to the response. For example, to return the location of the created resource when creating a resource:
Headers can also be created as TStrings objects and passed to the WebMock:
For a more detailed explanation, please visit: https://dev.to/rhatherall/series/3534