mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.09k stars 198 forks source link

mockConstruction doesn't work with coroutines #483

Open catsuperberg opened 1 year ago

catsuperberg commented 1 year ago

I'm in a situation where I'd rather test it how it is (object being instantiated inside a class) instead of refactoring object creation to be injected and found that i could use mockConstruction for this. The problem i have is i create this object inside a coroutine and as soon as you are in a coroutine you can't get the mock constructor, it just uses the default one. Documentation reads

it is possible to generate mocks on constructor invocations within the current thread and a user-defined scope

I tried to get thread IDs from outside and inside coroutine while running test and it seems to be the same.

Here is simple example where only instance outside the coroutine is created as a mock and code inside the mock tries to create the object using class constructor:

    @Test
    fun testMockConstructor() = runTest {
        val board = mockRetriever.getBoard(any(), any(), any())
        mockConstruction(TaskBoard::class.java).use { mock ->
            val outsideCoroutine = TaskBoard(board)
            println(outsideCoroutine.toString())
            this.launch {
                val insideCoroutine = TaskBoard(board)
                println(insideCoroutine.toString())
            }
            assertEquals(mock.constructed().size, 2)
        }
     }