https://kotlinlang.org logo
#ktor
Title
# ktor
e

Emirhan Emmez

12/06/2021, 10:19 AM
Hi, why am i getting 404 in test ?
Copy code
withTestApplication {
    handleRequest(HttpMethod.Get, "/hello").apply {
        assertEquals(HttpStatusCode.OK, response.status())
    }
}
a

Aleksei Tirman [JB]

12/06/2021, 10:20 AM
Could you please share your routing code?
e

Emirhan Emmez

12/06/2021, 10:21 AM
Copy code
route("/hello") {
    get {
        call.respondText(text = "Hello", status = HttpStatusCode.OK)
    }
}
a

Aleksei Tirman [JB]

12/06/2021, 10:22 AM
The following test passes:
Copy code
@Test
fun test() {
    withTestApplication {
        application.routing {
            route("/hello") {
                get {
                    call.respondText(text = "Hello", status = HttpStatusCode.OK)
                }
            }
        }

        handleRequest(HttpMethod.Get, "/hello").apply {
            assertEquals(HttpStatusCode.OK, response.status())
        }
    }
}
e

Emirhan Emmez

12/06/2021, 10:23 AM
should we declare all routes before the test?
a

Aleksei Tirman [JB]

12/06/2021, 10:24 AM
You need to apply them to a test application.
For example:
Copy code
class Test {
    @Test
    fun test() {
        withTestApplication {
            application.myRouting()

            handleRequest(HttpMethod.Get, "/hello").apply {
                assertEquals(HttpStatusCode.OK, response.status())
            }
        }
    }
}

fun Application.myRouting() {
    routing {
        route("/hello") {
            get {
                call.respondText(text = "Hello", status = HttpStatusCode.OK)
            }
        }
    }
}
This way you can apply routing to both real and test applications.
e

Emirhan Emmez

12/06/2021, 10:26 AM
Thx 🙂
Exception in thread "main" io.ktor.application.DuplicateApplicationFeatureException: Conflicting application feature is already installed with the same key as
ContentNegotiation
i think this 404 occurs because of this error
because i did what you said
a

Aleksei Tirman [JB]

12/06/2021, 1:49 PM
Please share a complete code for your test or a sample project.
20 Views