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"
}
Tags: #grails #micronaut