0
# Special Mocking
1
2
Advanced mocking capabilities for static methods, object instances, and constructors, enabling comprehensive testing of complex Kotlin constructs and language features.
3
4
## Capabilities
5
6
### Static Mocking
7
8
Mock static methods and properties of classes.
9
10
```kotlin { .api }
11
/**
12
* Mocks static methods of the specified classes
13
* @param classes Classes whose static methods should be mocked
14
*/
15
inline fun mockkStatic(vararg classes: KClass<*>)
16
17
/**
18
* Mocks static methods by class name
19
* @param classes Class names as strings
20
*/
21
inline fun mockkStatic(vararg classes: String)
22
23
/**
24
* Mocks static methods for the duration of a block
25
* @param classes Classes to mock
26
* @param block Block to execute with static mocking active
27
*/
28
inline fun mockkStatic(vararg classes: KClass<*>, block: () -> Unit)
29
30
/**
31
* Cancels static mocks
32
* @param classes Classes to unmock
33
*/
34
inline fun unmockkStatic(vararg classes: KClass<*>)
35
36
/**
37
* Cancels static mocks by class name
38
* @param classes Class names to unmock
39
*/
40
inline fun unmockkStatic(vararg classes: String)
41
```
42
43
**Usage Examples:**
44
45
```kotlin
46
// Static class to mock
47
class FileUtils {
48
companion object {
49
fun readFile(path: String): String = "real content"
50
fun writeFile(path: String, content: String): Boolean = true
51
}
52
}
53
54
// Mock static methods
55
mockkStatic(FileUtils::class)
56
57
// Stub static method
58
every { FileUtils.readFile("test.txt") } returns "mocked content"
59
every { FileUtils.writeFile("test.txt", any()) } returns true
60
61
// Use static methods - they're now mocked
62
val content = FileUtils.readFile("test.txt") // "mocked content"
63
val success = FileUtils.writeFile("test.txt", "data") // true
64
65
// Verify static method calls
66
verify { FileUtils.readFile("test.txt") }
67
verify { FileUtils.writeFile("test.txt", "data") }
68
69
// Clean up
70
unmockkStatic(FileUtils::class)
71
72
// Scoped static mocking
73
mockkStatic(FileUtils::class) {
74
every { FileUtils.readFile(any()) } returns "scoped mock"
75
val result = FileUtils.readFile("any.txt") // "scoped mock"
76
}
77
// Static mock automatically cleaned up after block
78
```
79
80
### Object Mocking
81
82
Mock Kotlin object instances (singletons).
83
84
```kotlin { .api }
85
/**
86
* Mocks Kotlin object instances
87
* @param objects Object instances to mock
88
* @param recordPrivateCalls If true, enables private call recording
89
*/
90
inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false)
91
92
/**
93
* Cancels object mocks
94
* @param objects Objects to unmock
95
*/
96
inline fun unmockkObject(vararg objects: Any)
97
98
/**
99
* Mocks objects for the duration of a block
100
* @param objects Objects to mock
101
* @param recordPrivateCalls If true, enables private call recording
102
* @param block Block to execute with object mocking active
103
*/
104
inline fun mockkObject(
105
vararg objects: Any,
106
recordPrivateCalls: Boolean = false,
107
block: () -> Unit
108
)
109
```
110
111
**Usage Examples:**
112
113
```kotlin
114
// Kotlin object to mock
115
object DatabaseConfig {
116
fun getConnectionString(): String = "real://connection"
117
fun getMaxConnections(): Int = 10
118
private fun validateConfig(): Boolean = true
119
}
120
121
// Mock the object
122
mockkObject(DatabaseConfig)
123
124
// Stub object methods
125
every { DatabaseConfig.getConnectionString() } returns "mock://connection"
126
every { DatabaseConfig.getMaxConnections() } returns 5
127
128
// Use the object - methods are now mocked
129
val connectionString = DatabaseConfig.getConnectionString() // "mock://connection"
130
val maxConnections = DatabaseConfig.getMaxConnections() // 5
131
132
// Verify object method calls
133
verify { DatabaseConfig.getConnectionString() }
134
verify { DatabaseConfig.getMaxConnections() }
135
136
// Clean up
137
unmockkObject(DatabaseConfig)
138
139
// Scoped object mocking
140
mockkObject(DatabaseConfig) {
141
every { DatabaseConfig.getConnectionString() } returns "scoped://mock"
142
val result = DatabaseConfig.getConnectionString() // "scoped://mock"
143
}
144
// Object mock automatically cleaned up after block
145
146
// Mock with private call recording
147
mockkObject(DatabaseConfig, recordPrivateCalls = true)
148
// Now private methods can be verified
149
```
150
151
### Constructor Mocking
152
153
Mock class constructors to return singleton instances.
154
155
```kotlin { .api }
156
/**
157
* Mocks constructors of the specified classes
158
* @param classes Classes whose constructors should be mocked
159
* @param recordPrivateCalls If true, enables private call recording
160
* @param localToThread If true, mocking is local to current thread
161
*/
162
inline fun mockkConstructor(
163
vararg classes: KClass<*>,
164
recordPrivateCalls: Boolean = false,
165
localToThread: Boolean = false
166
)
167
168
/**
169
* Cancels constructor mocks
170
* @param classes Classes to unmock
171
*/
172
inline fun unmockkConstructor(vararg classes: KClass<*>)
173
174
/**
175
* Mocks constructors for the duration of a block
176
* @param classes Classes whose constructors to mock
177
* @param recordPrivateCalls If true, enables private call recording
178
* @param localToThread If true, mocking is local to current thread
179
* @param block Block to execute with constructor mocking active
180
*/
181
inline fun mockkConstructor(
182
vararg classes: KClass<*>,
183
recordPrivateCalls: Boolean = false,
184
localToThread: Boolean = false,
185
block: () -> Unit
186
)
187
```
188
189
**Usage Examples:**
190
191
```kotlin
192
// Class to mock constructor for
193
class Logger(private val name: String) {
194
fun log(message: String) = println("[$name] $message")
195
fun error(message: String) = println("[$name] ERROR: $message")
196
}
197
198
class Service {
199
private val logger = Logger("Service") // This constructor call will be mocked
200
201
fun doWork() {
202
logger.log("Starting work")
203
logger.log("Work completed")
204
}
205
}
206
207
// Mock Logger constructor
208
mockkConstructor(Logger::class)
209
210
// Stub methods on the constructor-created instance
211
every { anyConstructed<Logger>().log(any()) } just Runs
212
every { anyConstructed<Logger>().error(any()) } just Runs
213
214
// Use the class - constructor creates mocked instances
215
val service = Service()
216
service.doWork() // Logger calls are now mocked
217
218
// Verify constructor calls and method calls
219
verify { anyConstructed<Logger>().log("Starting work") }
220
verify { anyConstructed<Logger>().log("Work completed") }
221
222
// Clean up
223
unmockkConstructor(Logger::class)
224
225
// Scoped constructor mocking
226
mockkConstructor(Logger::class) {
227
every { anyConstructed<Logger>().log(any()) } just Runs
228
val service = Service()
229
service.doWork() // Constructor mocked within this block
230
}
231
// Constructor mock automatically cleaned up after block
232
```
233
234
### JVM-Specific Extensions
235
236
Additional mocking capabilities available on JVM platform.
237
238
```kotlin { .api }
239
/**
240
* Mocks static functions by KFunction reference (JVM only)
241
* @param functions Static functions to mock
242
*/
243
fun mockkStatic(vararg functions: KFunction<*>)
244
245
/**
246
* Mocks static properties by KProperty reference (JVM only)
247
* @param properties Static properties to mock
248
*/
249
fun mockkStatic(vararg properties: KProperty<*>)
250
251
/**
252
* Extension property to get declaring class of top-level function (JVM only)
253
*/
254
val KFunction<*>.declaringKotlinFile: KClass<*>
255
```
256
257
**Usage Examples:**
258
259
```kotlin
260
// Top-level functions and properties
261
fun topLevelFunction(): String = "real value"
262
val topLevelProperty: String = "real property"
263
264
// Mock specific functions by reference (JVM only)
265
mockkStatic(::topLevelFunction)
266
every { topLevelFunction() } returns "mocked value"
267
268
// Use the function
269
val result = topLevelFunction() // "mocked value"
270
271
// Get declaring class of top-level function
272
val declaringClass = ::topLevelFunction.declaringKotlinFile
273
```
274
275
### Cleanup and Management
276
277
Functions for managing and cleaning up mocks.
278
279
```kotlin { .api }
280
/**
281
* Clears static mocks
282
* @param classes Classes to clear
283
* @param answers Clear stubbed answers (default: true)
284
* @param recordedCalls Clear recorded calls (default: true)
285
* @param childMocks Clear child mocks (default: true)
286
*/
287
inline fun clearStaticMockk(
288
vararg classes: KClass<*>,
289
answers: Boolean = true,
290
recordedCalls: Boolean = true,
291
childMocks: Boolean = true
292
)
293
294
/**
295
* Clears constructor mocks
296
* @param classes Classes to clear
297
* @param answers Clear stubbed answers (default: true)
298
* @param recordedCalls Clear recorded calls (default: true)
299
* @param childMocks Clear child mocks (default: true)
300
*/
301
inline fun clearConstructorMockk(
302
vararg classes: KClass<*>,
303
answers: Boolean = true,
304
recordedCalls: Boolean = true,
305
childMocks: Boolean = true
306
)
307
308
/**
309
* Cancels all mocks (objects, static, constructor)
310
*/
311
inline fun unmockkAll()
312
313
/**
314
* Clears all mocks with comprehensive filtering options
315
* @param answers Clear stubbed answers (default: true)
316
* @param recordedCalls Clear recorded calls (default: true)
317
* @param childMocks Clear child mocks (default: true)
318
* @param regularMocks Clear regular mocks (default: true)
319
* @param objectMocks Clear object mocks (default: true)
320
* @param staticMocks Clear static mocks (default: true)
321
* @param constructorMocks Clear constructor mocks (default: true)
322
* @param currentThreadOnly Only clear mocks for current thread (default: false)
323
*/
324
inline fun clearAllMocks(
325
answers: Boolean = true,
326
recordedCalls: Boolean = true,
327
childMocks: Boolean = true,
328
regularMocks: Boolean = true,
329
objectMocks: Boolean = true,
330
staticMocks: Boolean = true,
331
constructorMocks: Boolean = true,
332
currentThreadOnly: Boolean = false
333
)
334
```
335
336
**Usage Examples:**
337
338
```kotlin
339
// Setup various mocks
340
mockkStatic(FileUtils::class)
341
mockkObject(DatabaseConfig)
342
mockkConstructor(Logger::class)
343
344
// Clear specific mock types
345
clearStaticMockk(FileUtils::class)
346
clearConstructorMockk(Logger::class)
347
348
// Clear all mocks
349
unmockkAll()
350
351
// Clear all mocks with specific filtering
352
clearAllMocks(
353
answers = true,
354
recordedCalls = true,
355
staticMocks = true,
356
constructorMocks = false // Keep constructor mocks
357
)
358
```
359
360
### Special Mock Verification
361
362
Verification functions specific to special mocking types.
363
364
```kotlin { .api }
365
/**
366
* Reference to any constructed instance for verification
367
*/
368
fun <T : Any> anyConstructed(): T
369
370
/**
371
* Verify calls on constructed instances
372
*/
373
fun <T : Any> verifyConstructed(verifyBlock: MockKVerificationScope.() -> Unit)
374
```
375
376
**Usage Examples:**
377
378
```kotlin
379
mockkConstructor(Logger::class)
380
381
// Stub constructor-created instances
382
every { anyConstructed<Logger>().log(any()) } just Runs
383
384
// Create and use class that creates Logger instances
385
val service = Service()
386
service.doWork()
387
388
// Verify on any constructed instance
389
verify { anyConstructed<Logger>().log("Starting work") }
390
391
// Alternative verification syntax
392
verifyConstructed<Logger> {
393
log("Starting work")
394
log("Work completed")
395
}
396
```
397
398
### Thread Safety
399
400
Constructor mocking can be made thread-local for concurrent testing scenarios.
401
402
```kotlin { .api }
403
/**
404
* Thread-local constructor mocking
405
* @param localToThread If true, mocking only affects current thread
406
*/
407
inline fun mockkConstructor(
408
vararg classes: KClass<*>,
409
localToThread: Boolean = true
410
)
411
```
412
413
**Usage Examples:**
414
415
```kotlin
416
// Thread-local constructor mocking
417
mockkConstructor(Logger::class, localToThread = true)
418
419
// Mock only affects current thread
420
every { anyConstructed<Logger>().log(any()) } just Runs
421
422
// Other threads will use real constructors
423
thread {
424
val service = Service() // Uses real Logger constructor
425
service.doWork()
426
}
427
428
// Current thread uses mocked constructor
429
val service = Service() // Uses mocked Logger constructor
430
service.doWork()
431
```