Helper functions to work with Mockito in Kotlin
—
Fluent stubbing API with Kotlin DSL support, lambda-based configuration, and comprehensive response configuration. Essential for controlling mock behavior in Kotlin tests.
Core stubbing functions for configuring mock behavior.
/**
* Enables stubbing methods - use when you want the mock to return particular value
* Alias for Mockito.when with null-safe return
* @param methodCall The method call to stub
* @returns OngoingStubbing for configuring the response
*/
inline fun <T> whenever(methodCall: T): OngoingStubbing<T>Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Basic method stubbing
whenever(userService.findUser("john123")).thenReturn(johnUser)
// Method stubbing with arguments
whenever(calculator.add(5, 3)).thenReturn(8)Extension functions for configuring stubbed method responses.
/**
* Sets a return value to be returned when the method is called
* @param t The value to return
* @returns OngoingStubbing for method chaining
*/
infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T>
/**
* Sets consecutive return values to be returned when the method is called
* @param t First return value
* @param ts Additional return values for subsequent calls
* @returns OngoingStubbing for method chaining
*/
fun <T> OngoingStubbing<T>.doReturn(t: T, vararg ts: T): OngoingStubbing<T>
/**
* Sets consecutive return values from a list
* @param ts List of return values for consecutive calls
* @returns OngoingStubbing for method chaining
*/
inline infix fun <reified T> OngoingStubbing<T>.doReturnConsecutively(ts: List<T>): OngoingStubbing<T>Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Return specific value
whenever(userService.findUser(any())) doReturn johnUser
// Return consecutive values
whenever(idGenerator.nextId()).doReturn(1, 2, 3, 4, 5)
// Return values from list
val userIds = listOf(100, 101, 102)
whenever(userService.getNextUserId()) doReturnConsecutively userIdsFunctions for configuring methods to throw exceptions.
/**
* Sets Throwable objects to be thrown when the method is called
* @param t The throwable to throw
* @returns OngoingStubbing for method chaining
*/
infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T>
/**
* Sets multiple Throwable objects to be thrown on consecutive calls
* @param t First throwable to throw
* @param ts Additional throwables for subsequent calls
* @returns OngoingStubbing for method chaining
*/
fun <T> OngoingStubbing<T>.doThrow(
t: Throwable,
vararg ts: Throwable
): OngoingStubbing<T>
/**
* Sets a Throwable type to be thrown when the method is called
* @param t The throwable class to instantiate and throw
* @returns OngoingStubbing for method chaining
*/
infix fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>): OngoingStubbing<T>
/**
* Sets multiple Throwable classes to be thrown on consecutive calls
* @param t First throwable class to throw
* @param ts Additional throwable classes for subsequent calls
* @returns OngoingStubbing for method chaining
*/
fun <T> OngoingStubbing<T>.doThrow(
t: KClass<out Throwable>,
vararg ts: KClass<out Throwable>
): OngoingStubbing<T>Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Throw specific exception instance
val exception = RuntimeException("User not found")
whenever(userService.findUser("invalid")) doThrow exception
// Throw exception by class
whenever(userService.deleteUser(any())) doThrow IllegalStateException::class
// Throw consecutive exceptions
whenever(unstableService.call()).doThrow(
IOException("Network error"),
TimeoutException("Request timeout")
)Advanced stubbing using custom answer logic.
/**
* Sets a generic Answer for the method
* @param answer The Answer instance defining the response logic
* @returns OngoingStubbing for method chaining
*/
infix fun <T> OngoingStubbing<T>.doAnswer(answer: Answer<*>): OngoingStubbing<T>
/**
* Sets a generic Answer for the method using a lambda
* @param answer Lambda function receiving InvocationOnMock and returning response
* @returns OngoingStubbing for method chaining
*/
infix fun <T> OngoingStubbing<T>.doAnswer(answer: (InvocationOnMock) -> T?): OngoingStubbing<T>Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Answer with lambda accessing invocation details
whenever(calculator.add(any(), any())) doAnswer { invocation ->
val a = invocation.getArgument<Int>(0)
val b = invocation.getArgument<Int>(1)
a + b
}
// Answer with complex logic
whenever(userService.createUser(any())) doAnswer { invocation ->
val userData = invocation.getArgument<UserData>(0)
User(
id = generateId(),
name = userData.name,
email = userData.email,
createdAt = LocalDateTime.now()
)
}Kotlin DSL for fluent stubbing configuration.
/**
* Perform stubbing on a mock using DSL syntax
* @param mock The mock object to configure
* @param stubbing Lambda containing stubbing configuration
*/
inline fun <T> stubbing(
mock: T,
stubbing: KStubbing<T>.(T) -> Unit
)
/**
* Extension function for applying stubbing to a mock
* @param stubbing Lambda containing stubbing configuration
* @returns The mock object for method chaining
*/
inline fun <T : Any> T.stub(stubbing: KStubbing<T>.(T) -> Unit): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Configure stubbing with DSL
stubbing(userService) {
on { findUser(any()) } doReturn johnUser
on { isUserActive(any()) } doReturn true
}
// Extension function syntax
val configuredMock = userService.stub {
on { findUser("john123") } doReturn johnUser
on { findUser("jane456") } doReturn janeUser
}The core DSL class providing Kotlin-friendly stubbing methods.
/**
* Kotlin stubbing support class providing DSL for mock configuration
*/
class KStubbing<out T>(val mock: T) {
/**
* Stub a method call that has already been invoked
* @param methodCall The return value of the method call to stub
* @returns OngoingStubbing for configuring the response
*/
fun <R> on(methodCall: R): OngoingStubbing<R>
/**
* Stub a generic method call that may return null
* @param methodCall Lambda invoking the method to stub
* @param c KClass of the return type for type safety
* @returns OngoingStubbing for configuring the response
*/
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R>
/**
* Stub a generic method call with reified type parameter
* @param methodCall Lambda invoking the method to stub
* @returns OngoingStubbing for configuring the response
*/
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
/**
* Stub a method call using lambda syntax
* @param methodCall Lambda invoking the method to stub
* @returns OngoingStubbing for configuring the response
*/
fun <R> on(methodCall: T.() -> R): OngoingStubbing<R>
/**
* Stub a suspending/blocking method call
* @param m Suspending lambda invoking the method to stub
* @returns OngoingStubbing for configuring the response
*/
fun <T : Any, R> onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
}Usage Examples:
import com.nhaarman.mockitokotlin2.*
// Using KStubbing methods directly
val stubbing = KStubbing(userService)
// Stub with already invoked method
stubbing.on(userService.findUser("test")).doReturn(testUser)
// Stub with lambda syntax
stubbing.on { findUser(any()) }.doReturn(defaultUser)
// Stub generic method that might return null
stubbing.onGeneric<User> { findUserOptional(any()) }.doReturn(someUser)
// Stub suspending function
stubbing.onBlocking { loadUserAsync(any()) }.doReturn(asyncUser)Standalone stubber functions for complex stubbing scenarios.
/**
* Creates a stubber with custom answer logic
* @param answer Lambda function defining the response
* @returns Stubber for configuring method behavior
*/
fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber
/**
* Creates a stubber that calls the real method
* @returns Stubber that delegates to real implementation
*/
fun doCallRealMethod(): Stubber
/**
* Creates a stubber that does nothing (for void methods)
* @returns Stubber for void method configuration
*/
fun doNothing(): Stubber
/**
* Creates a stubber that returns a specific value
* @param value The value to return
* @returns Stubber for return value configuration
*/
fun doReturn(value: Any?): Stubber
/**
* Creates a stubber that returns consecutive values
* @param toBeReturned First value to return
* @param toBeReturnedNext Additional values for subsequent calls
* @returns Stubber for consecutive return configuration
*/
fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber
/**
* Creates a stubber that throws an exception of specified type
* @param toBeThrown The throwable class to instantiate and throw
* @returns Stubber for exception configuration
*/
fun doThrow(toBeThrown: KClass<out Throwable>): Stubber
/**
* Creates a stubber that throws specified exceptions
* @param toBeThrown The throwable instances to throw
* @returns Stubber for exception configuration
*/
fun doThrow(vararg toBeThrown: Throwable): Stubber
/**
* Extension function for applying stubber to a mock method
* @param mock The mock object to apply stubbing to
* @returns The mock object for method invocation
*/
fun <T> Stubber.whenever(mock: T): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Use stubber for pre-configured behavior
doReturn("default").whenever(userService).findUser(any())
doThrow(RuntimeException::class).whenever(userService).deleteUser(any())
doNothing().whenever(userService).logActivity(any())
// Call real method for partial mocking
doCallRealMethod().whenever(userService).validateUser(any())
// Complex answer with stubber
doAnswer<User> { invocation ->
val id = invocation.getArgument<String>(0)
User(id, "Generated User")
}.whenever(userService).findUser(anyString())// From org.mockito
interface OngoingStubbing<T>
interface Answer<T>
interface Stubber
class InvocationOnMock
class KClass<T>
// From mockito-kotlin
class KStubbing<out T>(val mock: T) {
fun <R> on(methodCall: R): OngoingStubbing<R>
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R>
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
fun <R> on(methodCall: T.() -> R): OngoingStubbing<R>
fun <T : Any, R> KStubbing<T>.onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
}Install with Tessl CLI
npx tessl i tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin