Kotest WireMock拡張

WireMock拡張について紹介する。

WireMockは、URL、header、body contentパターンなどに一致するHTTPレスポンスのスタブ(stubbing)を提供するライブラリである。

KotestはWireMockとの統合のためにkotest-extensions-wiremockモジュールを提供する。

開始するには、ビルドに次の依存関係を追加する必要がある。

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

この依存関係をクラスパスに含めると、WireMockListenerを使用できるようになる。WireMockListenerは、テスト中にWireMockServerのライフサイクルを管理する。

例:

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 ----------------
})

上の例では、Specのテストを実行する前にWireMockListenerを開始し、Specのすべてのテストを完了した後に停止するWireMockServerのインスタンスを作成した。

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 ----------------
})

上の例では、Specの各テストを実行する前にWireMockListenerを開始し、各テストを完了した後に停止するWireMockServerのインスタンスを作成した。WireMockServer.perTest(customerServiceServer)を使用して同じ結果を得ることができる。


参照