Skip to content

Instantly share code, notes, and snippets.

@dadouf
Last active February 25, 2020 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadouf/f9ec2b5d44f20295fcadb0e8834ad45a to your computer and use it in GitHub Desktop.
Save dadouf/f9ec2b5d44f20295fcadb0e8834ad45a to your computer and use it in GitHub Desktop.
Mockito+Kotlin: set mocks to throw unchecked exceptions
import org.mockito.BDDMockito
// Use just like a normal .willThrow:
// ```
// given(api.fetch()).willThrowUnchecked(Exception("First error"), Exception("Second error"))
// ```
fun <T> BDDMockito.BDDMyOngoingStubbing<T>.willThrowUnchecked(vararg throwables: Throwable) {
var invocationNumber = 0
this.willAnswer {
val throwableIndex = invocationNumber++.coerceAtMost(throwables.size - 1)
throw throwables[throwableIndex]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment