Kotestモックサーバー(MockServer)
MockServerは仮想HTTPサーバーを提供する。このライブラリを使用すると、別途Mockingライブラリ(mockkなど)を使用せず、実際のサーバーと通信するかのようにテストを行える。
KotestはMockServerライブラリとの統合のための拡張機能を提供する。
NOTE
ビルドに`io.kotest.extensions:kotest-extensions-mockserver`モジュールを追加する必要がある。
MockServer
MockServerは仮想HTTPサーバーを提供する。このライブラリを使用すると、別途Mockingライブラリ(mockkなど)を使用せず、実際のサーバーと通信するかのようにテストを行える。
KotestはMockServerライブラリとの統合のための拡張機能を提供する。
依存関係の追加
MockServerで使用するには、io.kotest.extensions:kotest-extensions-mockserverモジュールを依存関係に追加する必要がある。最新バージョンはMaven Centralで確認できる。
testImplementation("io.kotest.extensions:kotest-extensions-mockserver:<version>")
Configuration
モックサーバーを使用すると、テストしたいパスに対してハードコードされたインプロセスHTTPサーバーを定義できる。
Kotestで使用するには、テスト対象のSpecにMockServerListenerインスタンスをアタッチすると、Kotestが自動的にライフサイクルを制御する。
モックサーバー接続
その後、MockServerClientを使ってレスポンスを接続するだけでよい。
例:
class MyMockServerTest : FunSpec() {
init {
// this attaches the server to the lifeycle of the spec
listener(MockServerListener(1080))
// we can use the client to create routes. Here we are setting them up
// before each test by using the beforeTest callback.
beforeTest {
MockServerClient("localhost", 1080).`when`(
HttpRequest.request()
.withMethod("POST")
.withPath("/login")
.withHeader("Content-Type", "application/json")
.withBody("""{"username": "foo", "password": "bar"}""")
).respond(
HttpResponse.response()
.withStatusCode(202)
.withHeader("X-Test", "foo")
)
}
// this test will confirm the endpoint works
test("login endpoint should accept username and password json") {
// using the ktor client to send requests
val client = HttpClient(CIO)
val resp = client.post<io.ktor.client.statement.HttpResponse>("http://localhost:1080/login") {
contentType(ContentType.Application.Json)
body = """{"username": "foo", "password": "bar"}"""
}
// these handy matchers come from the kotest-assertions-ktor module
resp.shouldHaveStatus(HttpStatusCode.Accepted)
resp.shouldHaveHeader("X-Test", "foo")
}
}
}
上の例ではもちろんモックテスト自体だけをテストしているが、実際のテストをどのように構成できるかを示している。たとえば、テストしたいAPIクライアントがある場合、モックサーバーを使ってAPIパスを構成し、その後APIクライアントのメソッドを呼び出してレスポンスが正しく処理されるか確認できる。