Unit tests for Ktor with KMongo

621 Views Asked by At

How to make unit tests in Ktor with KMongo? How to mock database and make test on it? Let's say that I made simplest API like this:

private val client = KMongo.createClient().coroutine
private val database = client.getDatabase("dbName")
val people = database.getCollection<Person>()

suspend fun addPerson(person: Person): Boolean =
        people.insertOne(person).wasAcknowledged()

fun Route.addPersonRouting()
{
    route("/add")
    {
        post {
            if (addPerson(Person("Name", "Surname")))
            {
                call.respond(HttpStatusCode.OK, "ADDED")
            }
            else
            {
                call.respond(HttpStatusCode.OK, "NOT ADDED")
            }
        }
    }
}
@Test
fun `add person successfully`() = withTestApplication(
    {
        install(ContentNegotiation){ json() }
        routing { addPersonRouting() }  
    }
) {
    val c = handleRequest(HttpMethod.Post, "/add")
    assertEquals(HttpStatusCode.OK, c.response.status())
    assertEquals("ADDED", c.response.content)
}

Now I can write a unit test but the problem is that database used for this test is not clean so before every test I have to clean it. I was thinking if there is any built-in database so the Test class can use it and with every run, it gives me a new clean DB. If it is possible I can modify Routing so it takes interface/database and in the application, I can pass normal database and to the tests, I can use test database. Probably something very similar is used in Android Room Room.inMemoryDatabaseBuilder.

Would be nice if someone would show me step by step solution how to do this test with the clean mocked database without needing to clean it every time before running the test.

0

There are 0 best solutions below