mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 201 forks source link

How to make suspend function of a mock to throw a throwable #330

Closed giangpham96 closed 5 years ago

giangpham96 commented 5 years ago

As #205 pointed out, there is a way to mock the response of a suspend function. However, is there anyway to make them throw

Some of my attempts so far, but these didn't work as expected

whenever(object.callSuspendFunction("Batman", 2)) doThrow Exception()

object : MockedObject = mock {
            onBlocking {
                callSuspendFunction("Batman", 2)
            } doThrow Exception()
}

Looks like they throw immediately after the mocked call is defined

giangpham96 commented 5 years ago

the only work around I came up is to write the implementation for each mock

Nimrodda commented 5 years ago
  1. You should use OngoingStubbing style instead of Stubber
  2. Regarding the exception you throw, according to Mockito's docs:

    If throwables contain a checked exception then it has to match one of the checked exceptions of method signature.

In other words, use RuntimeException (or its extensions) or annotate the method under test with @Throws(YouException::class).

Example with RuntimeException: whenever(object.callSuspendFunction("Batman", 2)).thenThrow(RuntimeException::class.java)

giangpham96 commented 5 years ago

Thanks, it answers my question