import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.test.annotation.MicronautTest
import spock.lang.Specification
import javax.inject.Inject
@MicronautTest
class HelloControllerSpec extends Specification {
@Inject
EmbeddedServer embeddedServer (1)
@Inject
@Client("/")
HttpClient client (2)
void "test hello world response"() {
expect:
client.toBlocking() (3)
.retrieve(HttpRequest.GET('/hello')) == "Hello World" (4)
}
}
import io.micronaut.context.annotation.Property
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.test.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import javax.inject.Inject
@MicronautTest
class HelloControllerSpec {
@Inject
lateinit var server: EmbeddedServer (1)
@Inject
@field:Client("/")
lateinit var client: HttpClient (2)
@Test
fun testHelloWorldResponse() {
val rsp: String = client.toBlocking() (3)
.retrieve("/hello")
assertEquals("Hello World", rsp) (4)
}
}
In addition to a low-level client, Micronaut features a , powered by the Client annotation.
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
import io.reactivex.Single
@Client("/hello") (1)
interface HelloClient {
@Get(consumes = MediaType.TEXT_PLAIN) (2)
Single<String> hello() (3)
}
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
import io.reactivex.Single
@Client("/hello") (1)
interface HelloClient {
@Get(consumes = [MediaType.TEXT_PLAIN]) (2)
fun hello(): Single<String> (3)
To test the simply retrieve it from the associated with the server:
import io.micronaut.test.annotation.MicronautTest
import spock.lang.Specification
import javax.inject.Inject
@MicronautTest (1)
class HelloClientSpec extends Specification {
@Inject HelloClient client (2)
void "test hello world response"() {
expect:
client.hello().blockingGet() == "Hello World" (3)
}
}
import io.micronaut.context.annotation.Property
import io.micronaut.test.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import javax.inject.Inject
@MicronautTest (1)
class HelloClientSpec {
@Inject
lateinit var client: HelloClient (2)
@Test
fun testHelloWorldResponse() {
assertEquals("Hello World", client.hello().blockingGet())(3)
}
}
The Client annotation is very flexible. See the section on the for more information.