Skip to content

Latest commit

 

History

History
49 lines (32 loc) · 2.81 KB

README.adoc

File metadata and controls

49 lines (32 loc) · 2.81 KB

Testing Ratpack applications with Spock (20 minutes)

Write the following tests as specified under src/test/groovy. To run them, you can just run ./gradlew clean test

Unit testing

Unit testing does not require any special infrastructure. Moreover, Ratpack helps you providing a RequestFixture which can help you unit testing your handler.

It is particularly useful to have handlers in their own class, to be able to test them. For instance, you can use the following code to mock a JSON request to your handler, in a fluent API way:

HandlingResult result = RequestFixture.handle(new MyHandlerImpl()) { RequestFixture fixture ->
    fixture.body('{"foo":"bar"}', 'application/json').header('X-Auth-Token', 'sdfgdsfgdsfgdfg')
}

There are other useful methods in RequestFixture, like method() to specify the HTTP method, registry() to set values on the registry if your handler expects them and uri() and pathBinding() to specify the URL and the parameters in the request.

Have a look at the full documentation.

The returned value is of type HandlingResult, on which you can make assertions about the result of the execution of the handler.

So, given the UsernameHandler implementation, write a Spock unit test specification (UsernameHandlerSpec) that tests it with both empty and non-empty strings.

Functional testing

Functional testing in the context of a Ratpack app means to spin up a server instance, use an HTTP client to send requests and set assertions on the response received.

To make Ratpack start the application your tests, and to get an HTTP client, you can define the following attributes in your specification class:

@Shared ApplicationUnderTest aut = new GroovyRatpackMainApplicationUnderTest()
@Delegate TestHttpClient testClient = aut.httpClient

Note that by using Groovy’s @Delegate annotation, all the methods of the HTTP Client are available in your specification.

For this exercise, write a Spock specification (ApplicationSpec) that tests all the handlers defined in the chain DSL (Ratpack.groovy).