Hi everyone, I am learning ktor client by writting...
# ktor
c
Hi everyone, I am learning ktor client by writting ut. But when i wrote this test (below), it complains
first.url
was
<https://myhost.com/lv1/lv3/lv4/get_something>
Copy code
@Test
fun copyConfig_thenDefaultRequest_shouldCopyCurrentHttpClientConfig() = runTest {
    val mockEngine = installMockEngine {
        respondOk()
    }
    // when
    val newSut = sut
        .config {
            install(DefaultRequest) {
                url {
                    appendPathSegments("lv1", "lv2")
                }
            }
        }
    // then
    newSut.engine.shouldBeInstanceOf<MockEngine>()

    // when
    newSut.get("lv3/lv4/get_something")
    sut.get("get_something")
    // then
    val (first, second) = mockEngine.requestHistory
    first.url shouldBe Url("<https://myhost.com/lv1/lv2/lv3/lv4/get_something>")
    second.url shouldBe Url("<https://myhost.com/get_something>")
}
This snippet (below), however, works as expected.
Copy code
val newSut = sut
            .config { /* no-op */ }
            .apply {
                val plugin = plugin(HttpSend)
                plugin
                    .intercept { request ->
                        request.url {
                            val segments = it.pathSegments
                            it.path("lv1/lv2")
                            it.appendPathSegments(segments)
                        }
                        execute(request)
                    }
            }
Can anyone explain and how should i fix it? Many thanks 😊
a
That's because the default request URL is
<http://localhost/lv1/lv2>
and since it doesn't end with
/
, the
lv2
part is replaced with
lv3/lv4/get_something
. To solve the problem you can add the trailing
/
to the default URL by appending an empty component:
Copy code
install(DefaultRequest) {
    url {
        appendPathSegments("lv1", "lv2", "")
    }
}
💯 1
c
Nice. Thank you for your explanation and have a greate day :)