André Martins
04/26/2022, 10:52 AMcoEvery
to mock a specific function although somehow the coEvery
call is hanging when I run the test. What can cause this hanging?Mattia Tommasone
04/26/2022, 12:24 PMAndré Martins
04/26/2022, 2:13 PMMattia Tommasone
04/26/2022, 2:17 PMAndré Martins
04/26/2022, 2:20 PMCoroutineCollection
from KMongo and using this function that I’ve came up with to do it regarding this
inline fun <reified T : Any> mockkCoroutineCollection(
name: String? = null,
relaxed: Boolean = false,
vararg moreInterfaces: KClass<*>,
relaxUnitFun: Boolean = false,
block: MongoCollection<T>.() -> Unit = {}
): MongoCollection<T> = mockk(name, relaxed, *moreInterfaces, relaxUnitFun = relaxUnitFun) {
mockkStatic(MongoCollection<T>::coroutine)
val that = this
every { coroutine } returns mockk(name, relaxed, *moreInterfaces, relaxUnitFun = relaxUnitFun) {
every { collection } returns that
}
block()
}
And I have a service which receives the database and obtains both collections and seems that from the order I call it the mock doesn’t capture type informationdata class User(val id: Int, val name: String)
data class Book(val id: Int, val name: String)
class Service(private val myDatabase: CoroutineDatabase) {
private val userCollection: CoroutineCollection<User> = myDatabase.getCollection("users")
private val booksCollection: CoroutineCollection<Book> = myDatabase.getCollection("books")
fun getUserById(id: Int): User? = userCollection.findOneById(id)
fun getBookById(id: Int): Book? = booksCollection.findOneById(id)
// ...
}
fun test() {
val mongoDatabase = mockkCoroutineDatabase(relaxed = true)
val usersCollection = mockkCoroutineCollection<User>(relaxed = true)
val booksCollection = mockkCoroutineCollection<Book>(relaxed = true)
val coroutineUsers: CoroutineCollection<User> = usersCollection.coroutine
val coroutineBooks: CoroutineCollection<Book> = booksCollection.coroutine
every {
mongoDatabase.getCollection(any(), User::class.java)
} returns usersCollection
every {
mongoDatabase.getCollection(any(), Book::class.java)
} returns booksCollection
val sut: Service = Service(mongoDatabase)
val expectedUser = User(20, "Joe")
// depending on the order I create the mocked collections this hangs or not
coEvery {
coroutineUsers.findOneById(any())
} returns expectedUser
assertEquals(expectedUser, sut.getUserById(20))
}
mockkCoroutineCollection
this will passMattia Tommasone
04/26/2022, 2:40 PMMongoCollection<T>::coroutine
is static, so mockkStatic
-ing it more than once leads to recorded calls being erasedAndré Martins
04/26/2022, 2:41 PMevery { coroutine } returns …
doesn’t capture type informationevery { ofType<MongoCollection<T>>().coroutine } returns …
Mattia Tommasone
04/26/2022, 3:12 PMAndré Martins
04/26/2022, 3:13 PM