Testing Http Client (MockEngine)

预计阅读时间:1分钟

Ktor公开了一个用于HttpClient的MockEngine . 该引擎允许模拟HTTP调用,而无需实际连接到端点. 它允许设置一个代码块,该代码块可以处理请求并生成响应.

该引擎在工件io.ktor.client.engine.mock.MockEngine中的io.ktor:ktor-client-mock:$ktor_version,io.ktor:ktor-client-mock-jvm:$ktor_version,io.ktor:ktor-client-mock-js:$ktor_version,io.ktor:ktor-client-mock-native:$ktor_version类中定义io.ktor:ktor-client-mock:$ktor_version,io.ktor:ktor-client-mock-jvm:$ktor_version,io.ktor:ktor-client-mock-js:$ktor_version,io.ktor:ktor-client-mock-native:$ktor_version .
dependencies { api "io.ktor:ktor-client-mock:$ktor_version" api "io.ktor:ktor-client-mock-jvm:$ktor_version" api "io.ktor:ktor-client-mock-js:$ktor_version" api "io.ktor:ktor-client-mock-native:$ktor_version" }
dependencies { testCompile("io.ktor:ktor-client-mock:$ktor_version,io.ktor:ktor-client-mock-jvm:$ktor_version,io.ktor:ktor-client-mock-js:$ktor_version,io.ktor:ktor-client-mock-native:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-mock</artifactId> <version>${ktor.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-mock</artifactId> <version>${ktor.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-mock</artifactId> <version>${ktor.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-mock</artifactId> <version>${ktor.version}</version> <scope>test</scope> </dependency> </dependencies> </project>

Usage

用法是直截了当:MockEngine类有一个方法addHandlerMockEngineConfig ,接收一个块/回调将处理该请求. 此回调接收HttpRequest作为参数,并且必须返回HttpResponseData . 有许多帮助方法来构造响应.

完整的API描述和帮助程序方法列表可在此处找到.

一个示例说明了这一点:

val client = HttpClient(MockEngine) {
    engine {
        addHandler { request ->
            when (request.url.fullUrl) {
                "https://example.org/" -> {
                    val responseHeaders = headersOf("Content-Type" to listOf(ContentType.Text.Plain.toString()))
                    respond("Hello, world", headers = responseHeaders)
                }
                else -> error("Unhandled ${request.url.fullUrl}")
            }
        }
    }
}

private val Url.hostWithPortIfRequired: String get() = if (port == protocol.defaultPort) host else hostWithPort
private val Url.fullUrl: String get() = "${protocol.name}://$hostWithPortIfRequired$fullPath"

by  ICOPY.SITE