Ir al contenido principal
Versión: 5.2.x

MockServer

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Kotest ofrece una extensión para integrarse con la biblioteca MockServer.

nota

Requiere agregar el módulo io.kotest.extensions:kotest-extensions-mockserver a tu build.

MockServer permite definir un servidor HTTP en proceso con rutas predefinidas para realizar pruebas.

Para usarlo en Kotest, asociamos una instancia de MockServerListener al spec bajo prueba, y Kotest gestionará automáticamente su ciclo de vida.

Luego simplemente usamos MockServerClient para configurar las respuestas.

Por ejemplo:

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

En este ejemplo obviamente solo probamos el mock, pero ilustra cómo configurar pruebas reales. Por ejemplo, podrías tener un cliente de API para probar: configurarías las rutas de API con MockServer, invocarías métodos en tu cliente y verificarías que maneja correctamente las respuestas.