Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP server for unit tests in Delphi

I need to test some HTTP components in my Delphi app. I use DUnit and want to add some automation into testing.

So my testing code need to start the local HTTP server, configure it (for example, prepare for connection break in 3 seconds, or to simulate low bandwidth, or to ask for login/password etc), run my unit-tests and close HTTP server.

Are there some HTTP servers available exactly for Delphi/DUnit?

I know that Mozilla team have such server, but it's not too easy to integrate it into DUnit.

like image 851
Andrew Avatar asked Feb 27 '12 09:02

Andrew


2 Answers

I use Indy's TIdHttpServer to serve stuff in the same process.

This approach allows me to check that the requests coming in are correct, as well as checking the behaviour from the client end.

Also, you can individually set up the server on a testcase by testcase basis, making your unit tests easier to understand (meaning that you don't have a piece of the 'test' somewhere else).

like image 73
Nat Avatar answered Oct 31 '22 00:10

Nat


While @Nat's answer is workable, the setup code for stubbing requests and their associated responses using Indy can be pretty heavy. Also, when working in this way, I found the test code to be quite a time drain in both writing and debugging. Hence I built a framework Delphi WebMocks for DUnitX (sorry, not DUnit) to do exactly this with a syntax that should be straight-forward using HTTP terminology.

For example, the setup code is as simple as:

WebMock.StubRequest('GET', '/')
  .ToRespond
  .WithHeader('Content-Type', 'application/json')
  .WithBody('{ "value": 123 }');

You can also verify the requests actually got made like:

WebMock.Assert
  .Post('/')
  .WithHeader('Content-Type', 'application/json')
  .WithBody('{ "value": 123 }')
  .WasRequested;

If the assertion fails, it will fail the DUnitX test.

There is a lot more to it in terms of how you can specify request matching and responses so please check it out if you think you'd find it useful.

like image 20
R. Hatherall Avatar answered Oct 31 '22 00:10

R. Hatherall