Helper functions to work with Mockito in Kotlin
npx @tessl/cli install tessl/maven-com-nhaarman-mockitokotlin2--mockito-kotlin@2.2.00
# Mockito-Kotlin
1
2
Mockito-Kotlin is a small library that provides helper functions to work with Mockito in Kotlin. It offers Kotlin-friendly APIs, extension functions, and DSL syntax that address Kotlin's null safety and type inference limitations when using the Java-based Mockito framework. The library enables more idiomatic and concise test code in Kotlin projects.
3
4
## Package Information
5
6
- **Package Name**: mockito-kotlin
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Installation**: Add to your `build.gradle`: `testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"`
10
11
## Core Imports
12
13
```kotlin
14
import com.nhaarman.mockitokotlin2.*
15
```
16
17
Or selective imports:
18
19
```kotlin
20
import com.nhaarman.mockitokotlin2.mock
21
import com.nhaarman.mockitokotlin2.verify
22
import com.nhaarman.mockitokotlin2.whenever
23
import com.nhaarman.mockitokotlin2.any
24
```
25
26
## Basic Usage
27
28
```kotlin
29
import com.nhaarman.mockitokotlin2.*
30
31
@Test
32
fun doAction_doesSomething() {
33
// Given - Create mock with immediate stubbing
34
val mock = mock<MyClass> {
35
on { getText() } doReturn "text"
36
}
37
val classUnderTest = ClassUnderTest(mock)
38
39
// When
40
classUnderTest.doAction()
41
42
// Then
43
verify(mock).doSomething(any())
44
}
45
```
46
47
## Architecture
48
49
Mockito-Kotlin is organized around several key areas:
50
51
- **Mock Creation**: Type-safe mock creation with optional immediate stubbing
52
- **Argument Matching**: Kotlin-friendly argument matchers with reified generics
53
- **Verification**: Mockito verification with Kotlin extensions and coroutine support
54
- **Stubbing**: Fluent stubbing API with Kotlin DSL and lambda support
55
- **Spying**: Spy creation with type safety and immediate stubbing options
56
- **BDD Support**: Behavior-driven development style functions
57
58
## Capabilities
59
60
### Mock Creation
61
62
Type-safe mock creation with extensive configuration options and immediate stubbing support. Essential for setting up test doubles in Kotlin.
63
64
```kotlin { .api }
65
inline fun <reified T : Any> mock(
66
extraInterfaces: Array<out KClass<out Any>>? = null,
67
name: String? = null,
68
spiedInstance: Any? = null,
69
defaultAnswer: Answer<Any>? = null,
70
serializable: Boolean = false,
71
serializableMode: SerializableMode? = null,
72
verboseLogging: Boolean = false,
73
invocationListeners: Array<InvocationListener>? = null,
74
stubOnly: Boolean = false,
75
useConstructor: UseConstructor? = null,
76
outerInstance: Any? = null,
77
lenient: Boolean = false
78
): T
79
80
inline fun <reified T : Any> mock(
81
extraInterfaces: Array<out KClass<out Any>>? = null,
82
name: String? = null,
83
spiedInstance: Any? = null,
84
defaultAnswer: Answer<Any>? = null,
85
serializable: Boolean = false,
86
serializableMode: SerializableMode? = null,
87
verboseLogging: Boolean = false,
88
invocationListeners: Array<InvocationListener>? = null,
89
stubOnly: Boolean = false,
90
useConstructor: UseConstructor? = null,
91
outerInstance: Any? = null,
92
lenient: Boolean = false,
93
stubbing: KStubbing<T>.(T) -> Unit
94
): T
95
```
96
97
[Mock Creation](./mock-creation.md)
98
99
### Argument Matching
100
101
Powerful argument matchers designed for Kotlin's type system, providing type-safe matching with reified generics and null safety.
102
103
```kotlin { .api }
104
inline fun <reified T : Any> any(): T
105
inline fun <reified T : Any> anyOrNull(): T
106
inline fun <reified T : Any> anyVararg(): T
107
inline fun <reified T : Any?> anyArray(): Array<T>
108
inline fun <reified T : Any> argThat(noinline predicate: T.() -> Boolean): T
109
inline fun <reified T : Any> argThat(matcher: ArgumentMatcher<T>): T
110
inline fun <reified T : Any> argForWhich(noinline predicate: T.() -> Boolean): T
111
inline fun <reified T : Any> argWhere(noinline predicate: (T) -> Boolean): T
112
fun <T> eq(value: T): T
113
fun <T> same(value: T): T
114
inline fun <reified T : Any> isA(): T
115
fun <T : Any> isNull(): T?
116
fun <T : Any> isNotNull(): T?
117
fun <T : Any> notNull(): T?
118
inline fun <reified T : Any> refEq(value: T, vararg excludeFields: String): T
119
inline fun <reified T : Any> check(noinline predicate: (T) -> Unit): T
120
```
121
122
[Argument Matching](./argument-matching.md)
123
124
### Verification
125
126
Comprehensive verification system with support for coroutines, custom verification modes, and order-dependent verification.
127
128
```kotlin { .api }
129
fun <T> verify(mock: T): T
130
fun <T> verify(mock: T, mode: VerificationMode): T
131
fun <T> verifyBlocking(mock: T, f: suspend T.() -> Unit)
132
fun <T> verifyBlocking(mock: T, mode: VerificationMode, f: suspend T.() -> Unit)
133
fun <T> verifyNoMoreInteractions(vararg mocks: T)
134
fun verifyZeroInteractions(vararg mocks: Any)
135
fun <T> clearInvocations(vararg mocks: T)
136
fun times(numInvocations: Int): VerificationMode
137
fun atLeast(numInvocations: Int): VerificationMode
138
fun atLeastOnce(): VerificationMode
139
fun atMost(maxNumberOfInvocations: Int): VerificationMode
140
fun calls(wantedNumberOfInvocations: Int): VerificationMode
141
fun never(): VerificationMode
142
fun description(description: String): VerificationMode
143
fun after(millis: Long): VerificationAfterDelay
144
fun timeout(millis: Long): VerificationWithTimeout
145
fun ignoreStubs(vararg mocks: Any): Array<out Any>
146
fun only(): VerificationMode
147
fun inOrder(vararg mocks: Any): InOrder
148
inline fun inOrder(vararg mocks: Any, evaluation: InOrder.() -> Unit)
149
inline fun <T> T.inOrder(block: InOrderOnType<T>.() -> Any)
150
inline fun <T> verify(mock: T, block: VerifyScope<T>.() -> Unit)
151
```
152
153
[Verification](./verification.md)
154
155
### Stubbing
156
157
Fluent stubbing API with Kotlin DSL support, lambda-based configuration, and comprehensive response configuration.
158
159
```kotlin { .api }
160
inline fun <T> whenever(methodCall: T): OngoingStubbing<T>
161
infix fun <T> OngoingStubbing<T>.doReturn(t: T): OngoingStubbing<T>
162
infix fun <T> OngoingStubbing<T>.doThrow(t: Throwable): OngoingStubbing<T>
163
infix fun <T> OngoingStubbing<T>.doAnswer(answer: (InvocationOnMock) -> T?): OngoingStubbing<T>
164
165
class KStubbing<out T>(val mock: T) {
166
fun <R> on(methodCall: R): OngoingStubbing<R>
167
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
168
fun <T : Any, R> onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
169
}
170
```
171
172
[Stubbing](./stubbing.md)
173
174
### Argument Capturing
175
176
Type-safe argument capturing with Kotlin-friendly APIs and support for multiple argument capture patterns.
177
178
```kotlin { .api }
179
inline fun <reified T : Any> argumentCaptor(): KArgumentCaptor<T>
180
inline fun <reified T : Any> capture(captor: ArgumentCaptor<T>): T
181
182
class KArgumentCaptor<out T : Any?>(
183
private val captor: ArgumentCaptor<T>,
184
private val tClass: KClass<*>
185
) {
186
val firstValue: T
187
val lastValue: T
188
val allValues: List<T>
189
fun capture(): T
190
}
191
```
192
193
[Argument Capturing](./argument-capturing.md)
194
195
### Spying
196
197
Spy creation with type safety and immediate stubbing options for testing real objects with selective method stubbing.
198
199
```kotlin { .api }
200
inline fun <reified T : Any> spy(): T
201
inline fun <reified T : Any> spy(stubbing: KStubbing<T>.(T) -> Unit): T
202
fun <T> spy(value: T): T
203
inline fun <reified T> spy(value: T, stubbing: KStubbing<T>.(T) -> Unit): T
204
```
205
206
[Spying](./spying.md)
207
208
### Stubber Functions
209
210
Flexible stubbing configuration functions for advanced mock behavior setup.
211
212
```kotlin { .api }
213
fun <T> doAnswer(answer: (InvocationOnMock) -> T?): Stubber
214
fun doCallRealMethod(): Stubber
215
fun doNothing(): Stubber
216
fun doReturn(value: Any?): Stubber
217
fun doReturn(toBeReturned: Any?, vararg toBeReturnedNext: Any?): Stubber
218
fun doThrow(toBeThrown: KClass<out Throwable>): Stubber
219
fun doThrow(vararg toBeThrown: Throwable): Stubber
220
fun <T> Stubber.whenever(mock: T): OngoingStubbing<T>
221
```
222
223
### BDD Support
224
225
Behavior-driven development style functions providing Given-When-Then syntax for more expressive tests.
226
227
```kotlin { .api }
228
fun <T> given(methodCall: T): BDDMyOngoingStubbing<T>
229
fun <T> given(methodCall: () -> T): BDDMyOngoingStubbing<T>
230
fun <T> then(mock: T): BDDMockito.Then<T>
231
infix fun <T> BDDMyOngoingStubbing<T>.will(value: Answer<T>): BDDMyOngoingStubbing<T>
232
infix fun <T> BDDMyOngoingStubbing<T>.willAnswer(value: (InvocationOnMock) -> T?): BDDMyOngoingStubbing<T>
233
infix fun <T> BDDMyOngoingStubbing<T>.willReturn(value: () -> T): BDDMyOngoingStubbing<T>
234
infix fun <T> BDDMyOngoingStubbing<T>.willThrow(value: () -> Throwable): BDDMyOngoingStubbing<T>
235
```
236
237
### Core Utilities
238
239
Essential Mockito utility functions for mock management and validation.
240
241
```kotlin { .api }
242
fun validateMockitoUsage()
243
fun <T> reset(vararg mocks: T)
244
fun mockingDetails(toInspect: Any): MockingDetails
245
```
246
247
## Types
248
249
```kotlin { .api }
250
// Mockito-Kotlin specific types
251
class UseConstructor private constructor(val args: Array<Any>) {
252
companion object {
253
fun parameterless(): UseConstructor
254
fun withArguments(vararg arguments: Any): UseConstructor
255
}
256
}
257
258
class MockitoKotlinException(message: String?, cause: Throwable?) : RuntimeException(message, cause)
259
260
class VerifyScope<out T>(val mock: T) {
261
inline operator fun Int.times(call: T.() -> Unit)
262
}
263
264
class KStubbing<out T>(val mock: T) {
265
fun <R> on(methodCall: R): OngoingStubbing<R>
266
fun <R : Any> onGeneric(methodCall: T.() -> R?, c: KClass<R>): OngoingStubbing<R>
267
inline fun <reified R : Any> onGeneric(noinline methodCall: T.() -> R?): OngoingStubbing<R>
268
fun <R> on(methodCall: T.() -> R): OngoingStubbing<R>
269
fun <T : Any, R> onBlocking(m: suspend T.() -> R): OngoingStubbing<R>
270
}
271
272
class KArgumentCaptor<out T : Any?>(
273
private val captor: ArgumentCaptor<T>,
274
private val tClass: KClass<*>
275
) {
276
val firstValue: T
277
val secondValue: T
278
val thirdValue: T
279
val lastValue: T
280
val allValues: List<T>
281
fun capture(): T
282
}
283
284
// Imported Mockito types
285
typealias Answer<T> = org.mockito.stubbing.Answer<T>
286
typealias ArgumentCaptor<T> = org.mockito.ArgumentCaptor<T>
287
typealias ArgumentMatcher<T> = org.mockito.ArgumentMatcher<T>
288
typealias BDDMyOngoingStubbing<T> = org.mockito.BDDMockito.BDDMyOngoingStubbing<T>
289
typealias InOrder = org.mockito.InOrder
290
typealias InvocationListener = org.mockito.listeners.InvocationListener
291
typealias InvocationOnMock = org.mockito.invocation.InvocationOnMock
292
typealias MockSettings = org.mockito.MockSettings
293
typealias MockingDetails = org.mockito.MockingDetails
294
typealias OngoingStubbing<T> = org.mockito.stubbing.OngoingStubbing<T>
295
typealias SerializableMode = org.mockito.mock.SerializableMode
296
typealias Stubber = org.mockito.stubbing.Stubber
297
typealias VerificationAfterDelay = org.mockito.verification.VerificationAfterDelay
298
typealias VerificationMode = org.mockito.verification.VerificationMode
299
typealias VerificationWithTimeout = org.mockito.verification.VerificationWithTimeout
300
```