Kotest WireMock Extension

This page introduces the WireMock extension.

WireMock is a library that provides HTTP response stubbing based on URL, header, body content patterns, and more.

Kotest provides the kotest-extensions-wiremock module for integration with WireMock.

To get started, add the following dependency to your build:

io.kotest.extensions:kotest-extensions-wiremock:{version}

When this dependency is included on the classpath, WireMockListener becomes available. WireMockListener manages the lifecycle of WireMockServer during tests.

For example:

class SomeTest : FunSpec({
  val customerServiceServer = WireMockServer(9000)
  listener(WireMockListener(customerServiceServer, ListenerMode.PER_SPEC))

  test("let me get customer information") {
    customerServiceServer.stubFor(
      WireMock.get(WireMock.urlEqualTo("/customers/123"))
        .willReturn(WireMock.ok())
    )

    val connection = URL("http://localhost:9000/customers/123").openConnection() as HttpURLConnection
    connection.responseCode shouldBe 200
  }

    //  ------------OTHER TEST BELOW ----------------
})

In the example above, an instance of WireMockServer is created. WireMockListener starts it before running the spec’s tests and stops it after all tests in the spec complete.

You can achieve the same result by using WireMockServer.perSpec(customerServiceServer).

class SomeTest : FunSpec({
  val customerServiceServer = WireMockServer(9000)
  listener(WireMockListener(customerServiceServer, ListenerMode.PER_TEST))

  test("let me get customer information") {
    customerServiceServer.stubFor(
      WireMock.get(WireMock.urlEqualTo("/customers/123"))
        .willReturn(WireMock.ok())
    )

    val connection = URL("http://localhost:9000/customers/123").openConnection() as HttpURLConnection
    connection.responseCode shouldBe 200
  }

  //  ------------OTHER TEST BELOW ----------------
})

In the example above, an instance of WireMockServer is created. WireMockListener starts it before every test in the spec and stops it after each test completes. You can achieve the same result by using WireMockServer.perTest(customerServiceServer).


References