Helper functions to work with Mockito in Kotlin
—
Spy creation with type safety and immediate stubbing options for testing real objects with selective method stubbing. Essential for partial mocking scenarios where you want to test real object behavior while controlling specific methods.
Functions for creating spies of real objects with type safety.
/**
* Creates a spy of the real object using the default constructor
* The spy calls real methods unless they are stubbed
* @returns Spy instance of type T
*/
inline fun <reified T : Any> spy(): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Create spy using default constructor
val userServiceSpy = spy<UserService>()
// Real methods are called unless stubbed
val result = userServiceSpy.findUser("john123") // Calls real methodCreates a spy with immediate stubbing configuration using DSL syntax.
/**
* Creates a spy of the real object with immediate stubbing configuration
* The spy calls real methods unless they are stubbed
* @param stubbing Lambda for configuring spy behavior immediately after creation
* @returns Configured spy instance of type T
*/
inline fun <reified T : Any> spy(stubbing: KStubbing<T>.(T) -> Unit): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Create spy with immediate stubbing
val userServiceSpy = spy<UserService> {
on { findUser("testUser") } doReturn testUser
on { isUserActive(any()) } doReturn true
}
// Real methods called for non-stubbed calls
val realUser = userServiceSpy.findUser("realUser") // Calls real method
val testUser = userServiceSpy.findUser("testUser") // Returns stubbed valueCreates a spy from an existing object instance.
/**
* Creates a spy of the provided real object instance
* The spy calls real methods unless they are stubbed
* @param value The real object instance to spy on
* @returns Spy wrapping the provided instance
*/
fun <T> spy(value: T): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Create spy from existing instance
val realUserService = UserService(userRepository, emailService)
val userServiceSpy = spy(realUserService)
// Spy wraps the real instance
val user = userServiceSpy.findUser("john123") // Delegates to real instanceCreates a spy from an existing instance with immediate stubbing configuration.
/**
* Creates a spy of the provided real object instance with immediate stubbing
* The spy calls real methods unless they are stubbed
* @param value The real object instance to spy on
* @param stubbing Lambda for configuring spy behavior immediately after creation
* @returns Configured spy wrapping the provided instance
*/
inline fun <reified T> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): TUsage Examples:
import com.nhaarman.mockitokotlin2.*
// Create configured spy from existing instance
val realUserService = UserService(userRepository, emailService)
val userServiceSpy = spy(realUserService) {
// Stub specific methods while keeping others real
on { findUser("testUser") } doReturn testUser
on { sendWelcomeEmail(any()) } doNothing()
}
// Mix of real and stubbed behavior
val realUser = userServiceSpy.findUser("realUser") // Calls real method
val testUser = userServiceSpy.findUser("testUser") // Returns stubbed value
userServiceSpy.sendWelcomeEmail(testUser) // Does nothing (stubbed)Spies are ideal for partial mocking where you want to test most of the real behavior but control specific methods.
import com.nhaarman.mockitokotlin2.*
@Test
fun testUserRegistration() {
// Spy on real service but stub external dependencies
val userServiceSpy = spy(UserService(userRepository, emailService)) {
// Stub external email service call
on { sendWelcomeEmail(any()) } doReturn true
// Keep all other methods real
}
// Test real registration logic with stubbed email
val result = userServiceSpy.registerUser(newUserData)
// Verify real method was called
verify(userServiceSpy).saveUser(any())
// Verify stubbed method was called
verify(userServiceSpy).sendWelcomeEmail(any())
assertThat(result).isNotNull()
}Verify that real methods are called with expected arguments while maintaining real behavior.
import com.nhaarman.mockitokotlin2.*
@Test
fun testCachingBehavior() {
val userServiceSpy = spy<UserService>()
// Call method multiple times
userServiceSpy.findUser("john123")
userServiceSpy.findUser("john123")
userServiceSpy.findUser("jane456")
// Verify caching behavior
verify(userServiceSpy, times(2)).findUser("john123")
verify(userServiceSpy, times(1)).findUser("jane456")
}Stub specific methods to throw exceptions while keeping other behavior real.
import com.nhaarman.mockitokotlin2.*
@Test
fun testErrorHandling() {
val userServiceSpy = spy<UserService> {
// Simulate database failure for specific user
on { findUser("errorUser") } doThrow RuntimeException("Database error")
}
// Test error handling
assertThrows<RuntimeException> {
userServiceSpy.findUser("errorUser")
}
// Other users work normally
val normalUser = userServiceSpy.findUser("normalUser")
assertThat(normalUser).isNotNull()
}Use spies to test integration between components while controlling external dependencies.
import com.nhaarman.mockitokotlin2.*
@Test
fun testOrderProcessing() {
val paymentServiceSpy = spy(PaymentService(paymentGateway)) {
// Stub external payment gateway
on { processPayment(any()) } doReturn PaymentResult.success("txn123")
}
val orderService = OrderService(orderRepository, paymentServiceSpy)
// Test real order processing with stubbed payment
val result = orderService.processOrder(testOrder)
// Verify real order processing occurred
assertThat(result.status).isEqualTo(OrderStatus.COMPLETED)
// Verify payment service interaction
verify(paymentServiceSpy).processPayment(testOrder.paymentInfo)
}// From mockito-kotlin
class KStubbing<out T>(val mock: T)
// Standard Kotlin types
interface AnyInstall with Tessl CLI
npx tessl i tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin