Writing Tests
Unit tests can be written in 2 ways for a Crow application.
The handler method¶
Crow allows users to handle requests that may not come from the network. This is done by calling the handle(req, res)
method and providing a request and response objects. Which causes crow to identify and run the appropriate handler, returning the resulting response.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Note
This method is the simpler of the two and is usually all you really need to test your routes.
Warning
This method does not send any data, nor does it run any post handle code, so things like static file serving (as far as sending the actual data) or compression cannot be tested using this method.
The client method¶
This method involves creating a simple ASIO client that sends the request and receives the response. It is considerably more complex than the earlier method, but it is both more realistic and includes post handle operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
The second part is launching the app asynchronously and waiting until it starts.
The third is formulating our HTTP request string, the format is:
METHOD /
Content-Length:123
header1:value1
header2:value2
BODY
io_service
is created, then a TCP socket is created with the io_service
and is connected to the application.Then send the HTTP request string through the socket inside a buffer, and read the result into the buffer in
line 1
.Finally check the result against the expected one.
Warning
Be absolutely sure that the line app.stop()
runs, whether the test fails or succeeds. Not running it WILL CAUSE OTHER TESTS TO FAIL AND THE TEST TO HANG UNTIL THE PROCESS IS TERMINATED.