mockito / mockito-kotlin

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

Phantom call with suspend and try block #506

Closed furstenheim closed 2 months ago

furstenheim commented 6 months ago

I've stumbled upon this weird behavior with kotlin and mockito.

If I use both a suspend function and a try catch or try finally block. mockingDetails shows twice

import org.mockito.kotlin.spy
import org.mockito.kotlin.mockingDetails
import kotlinx.coroutines.withContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Dispatchers

...

    class A {
        // Shows twice
        suspend fun b (b:Int): Unit {
            try {
                withContext(Dispatchers.IO) {
                    println(b)
                }
            } finally {

            }
        }

        // Shows once
        fun c (b:Int): Unit {
            try {
                println(b)
            } finally {

            }
        }

        // Shows twice
        suspend fun d (b:Int): Unit {
            try {
                withContext(Dispatchers.IO) {
                    println(b)
                }
            } catch (e: Exception) {

            }
        }
        // Shows once
        suspend fun e (b:Int): Unit {
            withContext(Dispatchers.IO) {
                println(b)
            }
        }
    }
    @Test
    fun `Double mocking details`(): Unit = runBlocking {
        val a = spy(A())
        a.b(1)
        a.c(1)
        a.d(1)
        a.e(1)
        mockingDetails(a).invocations.forEach { println("1Test $it") }
    }

The result is:

1Test a.b(1);
1Test a.b(0);
1Test a.c(1);
1Test a.d(1);
1Test a.d(0);
1Test a.e(1)
TWiStErRob commented 2 months ago

@TimvdLippe I think this belongs in the mockito repo (move), and is potentially a duplicate / better visible repro of https://github.com/mockito/mockito/issues/1572; and is very likely related to https://github.com/mockito/mockito/issues/1869

TimvdLippe commented 2 months ago

Duplicate of mockito/mockito/issues/1572