Good morning / good afternoon / good evening! I ha...
# ktor
d
Good morning / good afternoon / good evening! I have a question regarding testing endpoints in ktor and the “new” testApplication. Last time I worked with ktor testApplication didn’t exist. I have this test
Copy code
@Test
fun `when user user exists returns code 490`() : Unit = testApplication {
    val client = createClient {
        install(ContentNegotiation) {
            json()
        }
    }

    RepositoriesProvider.userRepository.add(User("", "username", "", false, 0, 0))

    val response = <http://client.post|client.post>("/signup") {
        contentType(ContentType.Application.Json)
        setBody(UserRequest("username", "password"))
    }
    assertThat(response.status).isEqualTo(HttpStatusCode.Conflict)
}
to test the end point. I define the testApplication and the client to install the ContentNegotiation. But I have two questions here: 1. Do I need to repeat the createClient code in every method? Is there any way I can wrap the testApplication with this initialization and use it in all the tests. 2. The instance of the userRepository object is different in this test than in the code when the endpoint is reached. Am I missing something in the initialization so I can use the same instance? Thanks in advance!
a
1. You can define a wrapper function that will call the
testApplication
function and configure a client. 2. Please try to switch the development mode off:
Copy code
@Test
fun test() = testApplication {
    environment {
        developmentMode = false
    }

    // ...
}
d
Thanks! The developmentMode off helped me for my issue 2. Not sure if I understand your solution to my question 1. You mean something like?
Copy code
fun testApplicationWrapper(block: suspend ApplicationTestBuilder.() -> Unit) {
    testApplication {
        environment {
            developmentMode = false
        }

        createClient {
            install(ContentNegotiation) {
                json()
            }
        }
    }
}
and then something like
Copy code
@Test
fun test() : Unit = testApplicationWrapper {
   ...
}
?
a
I meant something like this:
Copy code
fun myTest(test: suspend (HttpClient) -> Unit) = testApplication {
    environment {
        developmentMode = false
    }

    val client = createClient {
        install(ContentNegotiation) {
            json()
        }
    }

    test(client)
}
Copy code
@Test
fun test() = myTest { client ->
    assertEquals("OK", client.get("/").bodyAsText())
}
d
looks good. I’ll try it. Thanks a lot for the help!