mockito / mockito-kotlin

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

Can you please provide suspending shortcuts for do* style stubbing APIs? #461

Open fejesjoco opened 1 year ago

fejesjoco commented 1 year ago

Consider this sample:

  open class Foo {
    open suspend fun check(s: String): Int {
      delay(1)
      return s.length
    }
  }

  @Test
  fun bad() = runBlocking {
    val foospy = spy(Foo())
    foospy.stub { onBlocking { foospy.check(any()) } doReturn 42 }
    assertThat(foospy.check("a")).isEqualTo(42)
  }

  @Test
  fun good() = runBlocking {
    val foospy = spy(Foo())
    foospy.stub { runBlocking { doReturn(42).whenever(foospy).check(any()) } }
    assertThat(foospy.check("a")).isEqualTo(42)
  }

The bad method fails because foospy.check calls the real method with a null and that throws a NPE. The good method works because we use the doReturn style and that doesn't call the real method.

The onBlocking helper is only provided for the when-style stubbing. Can you please provide similar helper methods for doReturn and doAnswer? The sample shows how they can work, but I'm not sure about how they should be named. I'm assuming that the KStubbing class is meant to cover all the tricky cases that arise because of suspending functions.