mockito-kotlin icon indicating copy to clipboard operation
mockito-kotlin copied to clipboard

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

Open fejesjoco opened this issue 2 years ago • 0 comments

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.

fejesjoco avatar Sep 09 '22 11:09 fejesjoco