问题描述
如何使用 Ktor
在 KMongo
中进行单元测试?如何模拟数据库并对其进行测试?假设我制作了这样的最简单的 API:
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)
}
现在我可以编写一个单元测试,但问题是用于这个测试的数据库不干净,所以在每次测试之前我都必须清理它。我在想是否有任何内置数据库,以便 Test 类可以使用它,并且每次运行时,它都会给我一个新的干净数据库。如果可能,我可以修改路由,以便它需要接口/数据库,并且在应用程序中,我可以通过普通数据库和测试,我可以使用测试数据库。 Android Room Room.inMemoryDatabaseBuilder
中可能使用了非常相似的东西。
如果有人向我展示如何使用干净的模拟数据库进行此测试而无需每次在运行测试前都对其进行清理的分步解决方案,那就太好了。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)