eclipse-vertx / vertx-junit5

Testing Vert.x applications with JUnit 5
Apache License 2.0
42 stars 30 forks source link

How to verify the body of HTTP response? #64

Open tveon opened 4 years ago

tveon commented 4 years ago

This might be a trivial mistake on my side, but I have not been able to find any guide or documentation on the proper way to assert the body of an HTTP response.

My server is basically what you get from the starter:

package dk.tveon.learning.vertx_kotlin

import io.vertx.core.AbstractVerticle
import io.vertx.core.Promise
import io.vertx.ext.web.Router
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class MainVerticle : AbstractVerticle() {
  companion object {
    private val LOG: Logger = LoggerFactory.getLogger(MainVerticle::class.java)
    const val PORT = 8080
  }

  override fun start(startPromise: Promise<Void>) {
    val router = Router.router(vertx)
    router.get("/").handler { req ->
      req.response()
        .putHeader("content-type", "text/plain")
        .end("Hello from Vert.x!\n")
    }

    vertx
      .createHttpServer()
      .requestHandler(router)
      .listen(PORT) { http ->
        if (http.succeeded()) {
          LOG.info("HTTP server started on port $PORT")
          startPromise.complete()
        } else {
          LOG.error("HTTP server failed to start", http.cause())
          startPromise.fail(http.cause())
        }
      }
  }
}

And the test-class:

package dk.tveon.learning.vertx_kotlin

import io.vertx.core.Vertx
import io.vertx.junit5.VertxExtension
import io.vertx.junit5.VertxTestContext
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.nio.charset.StandardCharsets

@ExtendWith(VertxExtension::class)
class TestMainVerticle {
  companion object {
    @BeforeAll
    @JvmStatic
    fun deploy_verticle(vertx: Vertx, testContext: VertxTestContext) {
      vertx.deployVerticle(MainVerticle(), testContext.completing())
    }
  }

  @Test
  fun verticle_deployed(testContext: VertxTestContext) {
    testContext.completeNow()
  }

  @Test
  fun api_hello(vertx: Vertx, testContext: VertxTestContext) {
    vertx.createHttpClient()
      .getNow(MainVerticle.PORT, "localhost", "/") { async ->
        testContext.verify {
          if (async.succeeded()) {
            val response = async.result()
            assertEquals(200, response.statusCode())
            assertEquals("text/plain", response.headers().get("Content-Type"))
            response.bodyHandler { body ->
              //FIXME - this does not get verified!
              assertEquals("Hello from Vert.x!", body.toString(StandardCharsets.UTF_8))
            }
          } else {
            fail("Failed to call test endpoint", async.cause())
          }
        }
        testContext.completeNow()
      }
  }

}

Notice the missing \n in the assertEquals.

When running the test, I see the following output:

13:44:21.963 [Test worker] DEBUG io.vertx.core.logging.LoggerFactory - Using io.vertx.core.logging.SLF4JLogDelegateFactory
13:44:22.521 [vert.x-eventloop-thread-0] INFO  d.t.l.vertx_kotlin.MainVerticle - HTTP server started on port 8080
13:44:22.884 [vert.x-eventloop-thread-4] ERROR i.v.c.h.impl.HttpClientResponseImpl - org.opentest4j.AssertionFailedError: expected: <Hello from Vert.x!> but was: <Hello from Vert.x!
>
dk.tveon.learning.vertx_kotlin.TestMainVerticle > verticle_deployed(VertxTestContext) PASSED
dk.tveon.learning.vertx_kotlin.TestMainVerticle > api_hello(Vertx, VertxTestContext) PASSED

So - what is the correct way to verify the body of the response?

Versions:

kotlinVersion = '1.3.20'
vertxVersion = '4.0.0-milestone3'
junitJupiterEngineVersion = '5.4.0'
tveon commented 4 years ago

And I found the problem - this block:

            response.bodyHandler { body ->
              //FIXME - this does not get verified!
              assertEquals("Hello from Vert.x!", body.toString(StandardCharsets.UTF_8))
            }

should be

            response.bodyHandler { body ->
              testContext.verify {
                assertEquals("Hello from Vert.x!", body.toString(StandardCharsets.UTF_8))
              }
            }

pretty obvious when you know it...

tveon commented 4 years ago

BTW - I didn’t close the issue, as I think the documentation/examples needs to be updated - preferably to not also include other libs like the webclient or vertx-unit

jponge commented 4 years ago

Sure, please do not hesitate to offer pull-requests to improve the docs/examples!

BTW to test HTTP bodies it's easier to use the vertx-web-client as you can more easily extract text / json.