CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin

Helper functions to work with Mockito in Kotlin

Pending
Overview
Eval results
Files

spying.mddocs/

Spying

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.

Capabilities

Basic Spy Creation

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(): T

Usage 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 method

Spy with Immediate Stubbing

Creates 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): T

Usage 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 value

Spy from Existing Instance

Creates 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): T

Usage 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 instance

Spy from Instance with Stubbing

Creates 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): T

Usage 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)

Common Spy Usage Patterns

Partial Mocking

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()
}

Method Call Verification

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")
}

Exception Testing

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()
}

Integration Testing

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)
}

Types

// From mockito-kotlin
class KStubbing<out T>(val mock: T)

// Standard Kotlin types
interface Any

Install with Tessl CLI

npx tessl i tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin

docs

argument-capturing.md

argument-matching.md

index.md

mock-creation.md

spying.md

stubbing.md

verification.md

tile.json