Helper methods

We'll create two helper functions in our test, called get() and post(), which will issue GET and POST requests to our test server. 

We'll start with get():

private fun get(path: String): HttpResponse<Buffer> {
val d1 = CompletableDeferred<HttpResponse<Buffer>>()

val client = WebClient.create(vertx)
client.get(8080, "localhost", path).send {
d1.complete(it.result())
}

return runBlocking {
d1.await()
}
}

The second method, post(), will look very similar, but it will also have a request body parameter:


private fun post(path: String, body: String = ""): HttpResponse<Buffer> {
val d1 = CompletableDeferred<HttpResponse<Buffer>>()

val client = WebClient.create(vertx)
client.post(8080, "localhost", path).sendBuffer(Buffer.buffer(body), { res ->
d1.complete(res.result())
})

return runBlocking {
d1.await()
}
}

Both of those functions use coroutines and the default parameter values Kotlin provides.

You should write your own helper functions or alter those according to your needs. 

Another helper function that we'll need is startServer(), which we already mentioned in @BeforeClass. It should look something like this:

private fun startServer() {
val d1 = CompletableDeferred<String>()
vertx.deployVerticle(ServerVerticle(), {
d1.complete("OK")
})
runBlocking {
println("Server started")
d1.await()
}
}

We'll need two new extension functions for our convenience. Those functions will convert the server response to JSON:

private fun <T> HttpResponse<T>.asJson(): JsonNode {
return this.bodyAsBuffer().asJson()
}

private fun Buffer.asJson(): JsonNode {
return ObjectMapper().readTree(this.toString())
}

Now we're all set to write our first test:

@Test
fun `Tests that alive works`() {
val response = get("/alive")
assertEquals(response.statusCode(), 200)

val body = response.asJson()
assertEquals(body["alive"].booleanValue(), true)
}

Run ./gradlew test to check that this test passes.

Next, we'll write another test; this time for the cat's creation endpoint. 

At first, it will fail:

@Test
fun `Makes sure cat can be created`() {
val response = post("/api/v1/cats",
"""
{
"name": "Binky",
"age": 5
}
""")

assertEquals(response.statusCode(), 201)
val body = response.asJson()

assertNotNull(body["id"])
assertEquals(body["name"].textValue(), "Binky")
assertEquals(body["age"].intValue(), 5)
}

Note that our server returns the status code 501 Not Implemented, and doesn't return the cat ID.

We'll be fixing that in the next section when we discuss persistence in a database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.101