Ktor - Unit testing is throwing 404

Viewed 230

I have a simple program in Ktor. It runs perfectly, but when I run the unit testing class it only throws this error: "expected:<200 OK> but was:<404 Not Found>"

This is my unit test code:

class ApplicationTest {
@Test
fun testRoot() = testApplication {
    val response = client.get("/")
    assertEquals(HttpStatusCode.OK, response.status)
}

@Test
fun testStart() = testApplication {
    val response = client.post("/start")
    assertEquals(HttpStatusCode.OK, response.status)
}
}

This is my Application.kt:

const val enableHTTPS = false
const val portHTTP = 80
const val portHTTPS = 7001


lateinit var environment: ApplicationEngineEnvironment
fun main() {
    initEnvironment()

    embeddedServer(Netty, environment = environment).start(wait = true)
}

My routing file is:

fun Application.configureRouting() {
    routing {
        get {
            call.respond(ApiDetails())
        }

        post("/start") {
            call.response.status(HttpStatusCode.OK)
        }

        post("/move") {
            val gameDetails: GameDetails = call.receive()
            val move = BasicStrategy().move(gameDetails, application)

            call.respond(move)
        }

        post("/end") {
        }
    }
}

1 Answers

To test an application, its modules should be loaded to testApplication. Loading modules to testApplication depends on the way used to create a server: by using the application.conf configuration file or in code using the embeddedServer function.

If you have the application.conf file in the resources folder, testApplication loads all modules and properties specified in the configuration file automatically.

You can disable loading modules by customizing an environment for tests.

If you use embeddedServer, you can add modules to a test application manually using the application function:

fun testModule1() = testApplication {
    application {
        module1()
        module2()
    }
}

In your case:

class ApplicationTest {
@Test
fun testRoot() = testApplication {
    application {
        configureRouting()
    }
    environment {
        config = MapApplicationConfig(
            "ktor.deployment.port" to "80",
            "ktor.deployment.sslPort" to "7001"
        )
    }
    val response = client.get("/")
    assertEquals(HttpStatusCode.OK, response.status)
}

@Test
fun testStart() = testApplication {
    application {
        configureRouting()
    }
    environment {
        config = MapApplicationConfig(
            "ktor.deployment.port" to "80",
            "ktor.deployment.sslPort" to "7001"
        )
    }
    val response = client.post("/start")
    assertEquals(HttpStatusCode.OK, response.status)
}

}

Related