Test a Grails Application with Micronaut HTTP Client

To use a Micronaut HTTP Client to test the API exposed by your Grails application you can use the following parent class for your integration tests:

package example

import io.micronaut.http.client.BlockingHttpClient
import io.micronaut.http.client.HttpClient
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Stepwise

abstract class ClientSpec extends Specification {

    @Shared
    HttpClient _httpClient

    @Shared
    BlockingHttpClient _client

    HttpClient getHttpClient() {
        if (_httpClient == null) {
            _httpClient = createHttpClient()
        }
        _httpClient
    }

    BlockingHttpClient getClient() {
        if (_client == null) {
            _client = getHttpClient().toBlocking()
        }
        _client
    }

    HttpClient createHttpClient() {
        String baseUrl = "http://localhost:$serverPort"
        HttpClient.create(baseUrl.toURL())
    }

    def cleanupSpec() {
        resetHttpClient()
    }

    void resetHttpClient() {
        _httpClient?.close()
        _httpClient = null
        _client = null
    }
}

A example test in src/integrationTest/groovy:

@Integration
class ApiContactControllerSpec extends ClientSpec {

    void "/apiContact is not a valid path"() {
        when:
        client.exchange(HttpRequest.GET('/apiContact'))

        then:
        HttpClientResponseException e = thrown()
        e.status == HttpStatus.NOT_FOUND
    }
}

You will need the following dependencies in build.gradle:

...
dependencies {
    ...
    ..
    testImplementation "io.micronaut:micronaut-inject-groovy"
    testImplementation "io.micronaut:micronaut-http-client"
}

My next events:
๐Ÿ—“ May 27 09:00 AWS Dublin - Micronaut and AWS Lambda
๐Ÿ—“ Jul 20 09:00 Workshop Security in the Micronaut Framework
๐Ÿ—“ Sep 20 09:00 JCON Online 2022 - Getting Started with the Micronaut Framework
๐Ÿ—“ Sep 23 09:00 JCON Online 2022 - Micronautยฎ Framework and Microstream Java-native persistence engine

Tags: #grails #micronaut
Sep 2021, 22.