0
# Stubbing
1
2
Fluent stubbing API with Kotlin DSL support, lambda-based configuration, and comprehensive response configuration. Essential for controlling mock behavior in Kotlin tests.
3
4
## Capabilities
5
6
### Basic Stubbing
7
8
Core stubbing functions for configuring mock behavior.
9
10
```kotlin { .api }
11
/**
12
* Enables stubbing methods - use when you want the mock to return particular value
13
* Alias for Mockito.when with null-safe return
14
* @param methodCall The method call to stub
15
* @returns OngoingStubbing for configuring the response
16
*/
17
inline fun <T> whenever(methodCall: T): OngoingStubbing<T>
18
```
19
20
**Usage Examples:**
21
22
```kotlin
23
import com.nhaarman.mockitokotlin2.*
24
25
// Basic method stubbing
26
whenever(userService.findUser("john123")).thenReturn(johnUser)
27
28
// Method stubbing with arguments
29
whenever(calculator.add(5, 3)).thenReturn(8)
30
```
31
32
### Stubbing Configuration
33
34
Extension functions for configuring stubbed method responses.
35
36
```kotlin { .api }
37
/**
38
* Sets a return value to be returned when the method is called
39
* @param t The value to return
40
* @returns OngoingStubbing for method chaining
41
*/
42
infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T>
43
44
/**
45
* Sets consecutive return values to be returned when the method is called
46
* @param t First return value
47
* @param ts Additional return values for subsequent calls
48
* @returns OngoingStubbing for method chaining
49
*/
50
fun <T> OngoingStubbing<T>.doReturn(t: T, vararg ts: T): OngoingStubbing<T>
51
52
/**
53
* Sets consecutive return values from a list
54
* @param ts List of return values for consecutive calls
55
* @returns OngoingStubbing for method chaining
56
*/
57
inline infix fun <reified T> OngoingStubbing<T>.doReturnConsecutively(ts: List<T>): OngoingStubbing<T>
58
```
59
60
**Usage Examples:**
61
62
```kotlin
63
import com.nhaarman.mockitokotlin2.*
64
65
// Return specific value
66
whenever(userService.findUser(any())) doReturn johnUser
67
68
// Return consecutive values
69
whenever(idGenerator.nextId()).doReturn(1, 2, 3, 4, 5)
70
71
// Return values from list
72
val userIds = listOf(100, 101, 102)
73
whenever(userService.getNextUserId()) doReturnConsecutively userIds
74
```
75
76
### Exception Stubbing
77
78
Functions for configuring methods to throw exceptions.
79
80
```kotlin { .api }
81
/**
82
* Sets Throwable objects to be thrown when the method is called
83
* @param t The throwable to throw
84
* @returns OngoingStubbing for method chaining
85
*/
86
infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T>
87
88
/**
89
* Sets multiple Throwable objects to be thrown on consecutive calls
90
* @param t First throwable to throw
91
* @param ts Additional throwables for subsequent calls
92
* @returns OngoingStubbing for method chaining
93
*/
94
fun <T> OngoingStubbing<T>.doThrow(
95
t: Throwable,
96
vararg ts: Throwable
97
): OngoingStubbing<T>
98
99
/**
100
* Sets a Throwable type to be thrown when the method is called
101
* @param t The throwable class to instantiate and throw
102
* @returns OngoingStubbing for method chaining
103
*/
104
infix fun <T> OngoingStubbing<T>.doThrow(t: KClass<out Throwable>): OngoingStubbing<T>
105
106
/**
107
* Sets multiple Throwable classes to be thrown on consecutive calls
108
* @param t First throwable class to throw
109
* @param ts Additional throwable classes for subsequent calls
110
* @returns OngoingStubbing for method chaining
111
*/
112
fun <T> OngoingStubbing<T>.doThrow(
113
t: KClass<out Throwable>,
114
vararg ts: KClass<out Throwable>
115
): OngoingStubbing<T>
116
```
117
118
**Usage Examples:**
119
120
```kotlin
121
import com.nhaarman.mockitokotlin2.*
122
123
// Throw specific exception instance
124
val exception = RuntimeException("User not found")
125
whenever(userService.findUser("invalid")) doThrow exception
126
127
// Throw exception by class
128
whenever(userService.deleteUser(any())) doThrow IllegalStateException::class
129
130
// Throw consecutive exceptions
131
whenever(unstableService.call()).doThrow(
132
IOException("Network error"),
133
TimeoutException("Request timeout")
134
)
135
```
136
137
### Answer-Based Stubbing
138
139
Advanced stubbing using custom answer logic.
140
141
```kotlin { .api }
142
/**
143
* Sets a generic Answer for the method
144
* @param answer The Answer instance defining the response logic
145
* @returns OngoingStubbing for method chaining
146
*/
147
infix fun <T> OngoingStubbing<T>.doAnswer(answer: Answer<*>): OngoingStubbing<T>
148
149
/**
150
* Sets a generic Answer for the method using a lambda
151
* @param answer Lambda function receiving InvocationOnMock and returning response
152
* @returns OngoingStubbing for method chaining
153
*/
154
infix fun <T> OngoingStubbing<T>.doAnswer(answer: (InvocationOnMock) -> T?): OngoingStubbing<T>
155
```
156
157
**Usage Examples:**
158
159
```kotlin
160
import com.nhaarman.mockitokotlin2.*
161
162
// Answer with lambda accessing invocation details
163
whenever(calculator.add(any(), any())) doAnswer { invocation ->
164
val a = invocation.getArgument<Int>(0)
165
val b = invocation.getArgument<Int>(1)
166
a + b
167
}
168
169
// Answer with complex logic
170
whenever(userService.createUser(any())) doAnswer { invocation ->
171
val userData = invocation.getArgument<UserData>(0)
172
User(
173
id = generateId(),
174
name = userData.name,
175
email = userData.email,
176
createdAt = LocalDateTime.now()
177
)
178
}
179
```
180
181
### DSL Stubbing
182
183
Kotlin DSL for fluent stubbing configuration.
184
185
```kotlin { .api }
186
/**
187
* Perform stubbing on a mock using DSL syntax
188
* @param mock The mock object to configure
189
* @param stubbing Lambda containing stubbing configuration
190
*/
191
inline fun <T> stubbing(
192
mock: T,
193
stubbing: KStubbing<T>.(T) -> Unit
194
)
195
196
/**
197
* Extension function for applying stubbing to a mock
198
* @param stubbing Lambda containing stubbing configuration
199
* @returns The mock object for method chaining
200
*/
201
inline fun <T : Any> T.stub(stubbing: KStubbing<T>.(T) -> Unit): T
202
```
203
204
**Usage Examples:**
205
206
```kotlin
207
import com.nhaarman.mockitokotlin2.*
208
209
// Configure stubbing with DSL
210
stubbing(userService) {
211
on { findUser(any()) } doReturn johnUser
212
on { isUserActive(any()) } doReturn true
213
}
214
215
// Extension function syntax
216
val configuredMock = userService.stub {
217
on { findUser("john123") } doReturn johnUser
218
on { findUser("jane456") } doReturn janeUser
219
}
220
```
221
222
### KStubbing Class
223
224
The core DSL class providing Kotlin-friendly stubbing methods.
225
226
```kotlin { .api }
227
/**
228
* Kotlin stubbing support class providing DSL for mock configuration
229
*/
230
class KStubbing<out T>(val mock: T) {
231
/**
232
* Stub a method call that has already been invoked
233
* @param methodCall The return value of the method call to stub
234
* @returns OngoingStubbing for configuring the response
235
*/
236
fun <R> on(methodCall: R): OngoingStubbing<R>
237
238
/**
239
* Stub a generic method call that may return null
240
* @param methodCall Lambda invoking the method to stub
241
* @param c KClass of the return type for type safety
242
* @returns OngoingStubbing for configuring the response
243
*/
244
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R>
245
246
/**
247
* Stub a generic method call with reified type parameter
248
* @param methodCall Lambda invoking the method to stub
249
* @returns OngoingStubbing for configuring the response
250
*/
251
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
252
253
/**
254
* Stub a method call using lambda syntax
255
* @param methodCall Lambda invoking the method to stub
256
* @returns OngoingStubbing for configuring the response
257
*/
258
fun <R> on(methodCall: T.() -> R): OngoingStubbing<R>
259
260
/**
261
* Stub a suspending/blocking method call
262
* @param m Suspending lambda invoking the method to stub
263
* @returns OngoingStubbing for configuring the response
264
*/
265
fun <T : Any, R> onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
266
}
267
```
268
269
**Usage Examples:**
270
271
```kotlin
272
import com.nhaarman.mockitokotlin2.*
273
274
// Using KStubbing methods directly
275
val stubbing = KStubbing(userService)
276
277
// Stub with already invoked method
278
stubbing.on(userService.findUser("test")).doReturn(testUser)
279
280
// Stub with lambda syntax
281
stubbing.on { findUser(any()) }.doReturn(defaultUser)
282
283
// Stub generic method that might return null
284
stubbing.onGeneric<User> { findUserOptional(any()) }.doReturn(someUser)
285
286
// Stub suspending function
287
stubbing.onBlocking { loadUserAsync(any()) }.doReturn(asyncUser)
288
```
289
290
### Advanced Stubber Functions
291
292
Standalone stubber functions for complex stubbing scenarios.
293
294
```kotlin { .api }
295
/**
296
* Creates a stubber with custom answer logic
297
* @param answer Lambda function defining the response
298
* @returns Stubber for configuring method behavior
299
*/
300
fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber
301
302
/**
303
* Creates a stubber that calls the real method
304
* @returns Stubber that delegates to real implementation
305
*/
306
fun doCallRealMethod(): Stubber
307
308
/**
309
* Creates a stubber that does nothing (for void methods)
310
* @returns Stubber for void method configuration
311
*/
312
fun doNothing(): Stubber
313
314
/**
315
* Creates a stubber that returns a specific value
316
* @param value The value to return
317
* @returns Stubber for return value configuration
318
*/
319
fun doReturn(value: Any?): Stubber
320
321
/**
322
* Creates a stubber that returns consecutive values
323
* @param toBeReturned First value to return
324
* @param toBeReturnedNext Additional values for subsequent calls
325
* @returns Stubber for consecutive return configuration
326
*/
327
fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber
328
329
/**
330
* Creates a stubber that throws an exception of specified type
331
* @param toBeThrown The throwable class to instantiate and throw
332
* @returns Stubber for exception configuration
333
*/
334
fun doThrow(toBeThrown: KClass<out Throwable>): Stubber
335
336
/**
337
* Creates a stubber that throws specified exceptions
338
* @param toBeThrown The throwable instances to throw
339
* @returns Stubber for exception configuration
340
*/
341
fun doThrow(vararg toBeThrown: Throwable): Stubber
342
343
/**
344
* Extension function for applying stubber to a mock method
345
* @param mock The mock object to apply stubbing to
346
* @returns The mock object for method invocation
347
*/
348
fun <T> Stubber.whenever(mock: T): T
349
```
350
351
**Usage Examples:**
352
353
```kotlin
354
import com.nhaarman.mockitokotlin2.*
355
356
// Use stubber for pre-configured behavior
357
doReturn("default").whenever(userService).findUser(any())
358
doThrow(RuntimeException::class).whenever(userService).deleteUser(any())
359
doNothing().whenever(userService).logActivity(any())
360
361
// Call real method for partial mocking
362
doCallRealMethod().whenever(userService).validateUser(any())
363
364
// Complex answer with stubber
365
doAnswer<User> { invocation ->
366
val id = invocation.getArgument<String>(0)
367
User(id, "Generated User")
368
}.whenever(userService).findUser(anyString())
369
```
370
371
## Types
372
373
```kotlin { .api }
374
// From org.mockito
375
interface OngoingStubbing<T>
376
interface Answer<T>
377
interface Stubber
378
class InvocationOnMock
379
class KClass<T>
380
381
// From mockito-kotlin
382
class KStubbing<out T>(val mock: T) {
383
fun <R> on(methodCall: R): OngoingStubbing<R>
384
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R>
385
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
386
fun <R> on(methodCall: T.() -> R): OngoingStubbing<R>
387
fun <T : Any, R> KStubbing<T>.onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
388
}
389
```