Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper functions for coroutine #470

Merged
merged 1 commit into from
Dec 18, 2022

Conversation

Rajin9601
Copy link
Contributor

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)
  1. Stubber.wheneverBlocking
// 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() }

Copy link
Contributor

@TimvdLippe TimvdLippe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great addition and good explanation of why these are useful!

@TimvdLippe TimvdLippe merged commit 513056e into mockito:main Dec 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants