mockito / mockito-kotlin

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

Add helper functions for coroutine #470

Closed Rajin9601 closed 1 year ago

Rajin9601 commented 1 year ago

For mocking suspending functions, current mockito-kotlin suggests two ways.

  1. wrapping test case with runBlocking
  2. using KStubbing.onBlocking function.

For stubbing non-suspending functions, developer can use Mockito.when or Mockito.doReturn style. If someone uses those style in their tests, whenever developer wants to change non-suspending function to suspending function, developer has to change the style of test code. This burden can be removed if mockito-kotlin supports those style of stubbing for suspending function.

This PR suggests some helper functions for mocking a coroutine function. This allows developer to use Mockito.when, Mockito.doReturn, BDD style for suspending functions. The syntax is similar to verifyBlocking which already exists in mockito-kotlin.

Helper functions this PR suggests.

  1. wheneverBlocking
    
    // normal function
    whenever(m.test())
    .doReturn(42)

// suggestion: for suspending function wheneverBlocking { m.suspending() } .doReturn(42)


2. Stubber.wheneverBlocking
```kotlin
// normal function
doReturn(10)
    .whenever(m).test()

// suggestion: for suspending function
doReturn(10)
    .wheneverBlocking(m) {
        delaying()
    }
  1. givenBlocking & shouldBlocking
    
    // normal function
    given(fixture.test()).willAnswer { 42 }

...

then(fixture).should().test()

// suggestion: for suspending function givenBlocking { fixture.suspending() }.willSuspendableAnswer { withContext(Dispatchers.Default) { 42 } }

...

then(fixture).shouldBlocking { suspending() }