Helper functions to work with Mockito in Kotlin
—
Comprehensive verification system with support for coroutines, custom verification modes, and order-dependent verification. Essential for validating mock interactions in Kotlin tests.
Core verification functions for validating mock interactions.
/**
* Verifies that certain behavior happened exactly once
* @param mock The mock object to verify
* @returns The mock object for method call verification
*/
fun <T> verify(mock: T): T
/**
* Verifies behavior with a specific verification mode
* @param mock The mock object to verify
* @param mode Verification mode (times, atLeast, never, etc.)
* @returns The mock object for method call verification
*/
fun <T> verify(mock: T, mode: VerificationMode): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Verify method was called once
verify(userService).findUser("john123")
// Verify method was called specific number of times
verify(userService, times(3)).findUser(any())
// Verify method was never called
verify(userService, never()).deleteUser(any())Special verification functions for suspending functions and coroutines.
/**
* Verifies certain suspending behavior happened exactly once
* Warning: Only one method call can be verified in the function
* @param mock The mock object to verify
* @param f Suspending lambda containing the method call to verify
*/
fun <T> verifyBlocking(mock: T, f: suspend T.() -> Unit)
/**
* Verifies suspending behavior with a specific verification mode
* Warning: Only one method call can be verified in the function
* @param mock The mock object to verify
* @param mode Verification mode (times, atLeast, never, etc.)
* @param f Suspending lambda containing the method call to verify
*/
fun <T> verifyBlocking(mock: T, mode: VerificationMode, f: suspend T.() -> Unit)Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Verify suspending function was called once
verifyBlocking(asyncUserService) {
loadUserAsync("john123")
}
// Verify suspending function with specific count
verifyBlocking(asyncUserService, times(2)) {
refreshUserData(any())
}Functions that create verification modes for controlling how verification is performed.
/**
* Allows verifying exact number of invocations
* @param numInvocations The exact number of expected invocations
* @returns VerificationMode for exact count verification
*/
fun times(numInvocations: Int): VerificationMode
/**
* Allows at-least-x verification
* @param numInvocations The minimum number of expected invocations
* @returns VerificationMode for minimum count verification
*/
fun atLeast(numInvocations: Int): VerificationMode
/**
* Allows at-least-once verification
* @returns VerificationMode for at-least-once verification
*/
fun atLeastOnce(): VerificationMode
/**
* Allows at-most-x verification
* @param maxNumberOfInvocations The maximum number of allowed invocations
* @returns VerificationMode for maximum count verification
*/
fun atMost(maxNumberOfInvocations: Int): VerificationMode
/**
* Allows non-greedy verification in order
* @param wantedNumberOfInvocations The number of invocations to verify
* @returns VerificationMode for ordered verification
*/
fun calls(wantedNumberOfInvocations: Int): VerificationMode
/**
* Alias for times(0) - verifies method was never called
* @returns VerificationMode for zero invocations
*/
fun never(): VerificationModeUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Verify exact number of calls
verify(userService, times(5)).findUser(any())
// Verify at least some calls
verify(userService, atLeast(1)).findUser(any())
verify(userService, atLeastOnce()).findUser(any())
// Verify at most some calls
verify(userService, atMost(3)).deleteUser(any())
// Verify never called
verify(userService, never()).deleteAllUsers()Functions for verifying overall interaction patterns with mocks.
/**
* Checks if any of given mocks has any unverified interaction
* @param mocks The mock objects to check for unverified interactions
*/
fun <T> verifyNoMoreInteractions(vararg mocks: T)
/**
* Verifies that no interactions happened on given mocks
* @param mocks The mock objects to verify had zero interactions
*/
fun verifyZeroInteractions(vararg mocks: Any)
/**
* Use this method to clear invocations when stubbing is non-trivial
* @param mocks The mock objects to clear invocations from
*/
fun <T> clearInvocations(vararg mocks: T)Usage Examples:
import com.nhaarman.mockitokotlin2.*
// After verifying specific calls, ensure no other interactions occurred
verify(userService).findUser("john123")
verify(userService).updateLastLogin(any())
verifyNoMoreInteractions(userService)
// Verify mock had no interactions at all
verifyZeroInteractions(unusedService)
// Clear previous interactions to start fresh verification
clearInvocations(userService)Functions for verifying the order of method invocations across multiple mocks.
/**
* Creates InOrder object that allows verifying mocks in order
* @param mocks The mock objects to verify in order
* @returns InOrder instance for ordered verification
*/
fun inOrder(vararg mocks: Any): InOrder
/**
* Creates InOrder object with immediate lambda evaluation
* @param mocks The mock objects to verify in order
* @param evaluation Lambda containing ordered verification calls
*/
inline fun inOrder(
vararg mocks: Any,
evaluation: InOrder.() -> Unit
)Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Verify calls happened in specific order
val inOrder = inOrder(userService, emailService)
inOrder.verify(userService).findUser("john123")
inOrder.verify(emailService).sendWelcomeEmail(any())
inOrder.verify(userService).updateLastLogin(any())
// Using lambda syntax
inOrder(userService, emailService) {
verify(userService).findUser("john123")
verify(emailService).sendWelcomeEmail(any())
}Extension function for convenient order verification on single mocks.
/**
* Allows InOrder verification for a single mocked instance
* @param block Lambda containing verification calls in expected order
*/
inline fun <T> T.inOrder(block: InOrderOnType<T>.() -> Any)
/**
* Helper class for single mock InOrder verification
*/
class InOrderOnType<T>(private val t: T) : InOrder by inOrder(t as Any) {
/**
* Creates verification proxy for the wrapped mock
* @returns The mock object for method call verification
*/
fun verify(): T
}Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Verify order of calls on single mock
userService.inOrder {
verify().findUser("john123")
verify().updateLastLogin(any())
verify().saveUser(any())
}Additional verification utilities and modes.
/**
* Adds a description to be printed if verification fails
* @param description Description text for failed verification
* @returns VerificationMode with description
*/
fun description(description: String): VerificationMode
/**
* Allows verifying over a given period - waits for desired interaction
* @param millis Time period to wait in milliseconds
* @returns VerificationAfterDelay for time-based verification
*/
fun after(millis: Long): VerificationAfterDelay
/**
* Allows verifying with timeout - waits up to specified time
* @param millis Timeout in milliseconds
* @returns VerificationWithTimeout for timeout-based verification
*/
fun timeout(millis: Long): VerificationWithTimeout
/**
* Ignores stubbed methods of given mocks for verification purposes
* @param mocks The mock objects whose stubs should be ignored
* @returns Array of mocks with stubs ignored
*/
fun ignoreStubs(vararg mocks: Any): Array<out Any>
/**
* Verifies that given method was the only one invoked
* @returns VerificationMode for exclusive invocation verification
*/
fun only(): VerificationModeUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Add description for better error messages
verify(userService, description("User service should find user"))
.findUser("john123")
// Wait for interaction to happen (for concurrent testing)
verify(asyncService, timeout(5000)).processData(any())
// Verify after delay (useful for eventual consistency)
verify(eventHandler, after(1000)).handleEvent(any())
// Verify only this method was called
verify(userService, only()).findUser("john123")
// Ignore stubbed methods when verifying
val mocksIgnoringStubs = ignoreStubs(userService, emailService)DSL-style verification with enhanced readability using scope blocks.
/**
* Verify multiple calls on mock using enhanced DSL syntax
* @param mock The mock object to verify
* @param block Lambda containing verification specifications
*/
inline fun <T> verify(mock: T, block: VerifyScope<T>.() -> Unit)
/**
* Scope class for DSL-style verification
*/
class VerifyScope<out T>(val mock: T) {
/**
* Times operator for specifying call count in DSL
* @param call Lambda containing the method call to verify
*/
inline operator fun Int.times(call: T.() -> Unit)
}Usage Examples:
import com.nhaarman.mockitokotlin2.*
// DSL-style verification with readable syntax
verify(userService) {
1 * { findUser("john123") }
2 * { updateLastLogin(any()) }
3 * { saveUser(any()) }
}Custom verification predicates for complex argument validation.
/**
* For usage with verification only. Performs actions to verify an argument
* @param predicate A function that performs actions to verify an argument T
* @returns Argument matcher that applies the predicate
*/
inline fun <reified T : Any> check(noinline predicate: (T) -> Unit): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
import org.junit.Assert.assertThat
import org.hamcrest.CoreMatchers.`is`
// Verify with custom predicate
verify(userService).processUser(check { user ->
assertThat(user.email, `is`("john@example.com"))
assertThat(user.age, `is`(25))
})
// Complex validation during verification
verify(orderService).createOrder(check { order ->
assertThat(order.items.size, `is`(3))
assertThat(order.total, `it`(greaterThan(100.0)))
})// From org.mockito
interface VerificationMode
interface InOrder
class VerificationAfterDelay
class VerificationWithTimeout
// From mockito-kotlin
class InOrderOnType<T>(private val t: T) : InOrder {
fun verify(): T
}
class VerifyScope<out T>(val mock: T) {
inline operator fun Int.times(call: T.() -> Unit)
}Install with Tessl CLI
npx tessl i tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin