Hey I’m getting an error when trying to mock a KMo...
# mockk
a
Hey I’m getting an error when trying to mock a KMongo
CoroutineCollection
with the following code
Copy code
data class User(val id: Int, val name: String)

class Service(private val myDatabase: CoroutineDatabase) {
    private val userCollection: CoroutineCollection<User> = myDatabase.getCollection("users")
    suspend fun getById(id: Int): User? = userCollection.findOneById(id)
    // ...
    suspend fun insertUser(user: User): InsertOneResult = userCollection.insertOne(user)
}

@Test
fun myTest(): Unit = runBlocking {
    // Arrange
    val database = mockk<CoroutineDatabase>()
    val userCol = mockk<CoroutineCollection<User>>()

    every {
        database.getCollection<User>("users")
    } returns userCol


    val service = Service(database)
    val expectedUser = User(30, "Joe")

    coEvery {
        userCol.findOneById(30)
    } returns expectedUser


    // Act
    val actualUser = service.getById(30)

    // Assert
    assertEquals(expectedUser, actualUser)
}
The error is
Copy code
class org.litote.kmongo.coroutine.CoroutineCollection cannot be cast to class com.mongodb.reactivestreams.client.MongoCollection (org.litote.kmongo.coroutine.CoroutineCollection and com.mongodb.reactivestreams.client.MongoCollection are in unnamed module of loader 'app')
I suspect this is due to functions like
CoroutineDatabase::getCollection<T>(String)
being inline
m
i don’t know much about KMongo, but you’re right, the fact that getCollection<T>(String) is inline is likely the cause for the issue you are facing
👍 1
a
After some testing and debug I’ve managed to get this working as I described here