0
# Mock Creation
1
2
Core mock and spy creation functions with comprehensive configuration options for creating different types of test doubles in Kotlin testing scenarios.
3
4
## Capabilities
5
6
### Regular Mock Creation
7
8
Creates a mock instance that replaces all methods with fake implementations.
9
10
```kotlin { .api }
11
/**
12
* Creates a mock for the specified class type
13
* @param name Optional name for the mock (useful for debugging)
14
* @param relaxed If true, unstubbed methods return default values instead of throwing
15
* @param moreInterfaces Additional interfaces for the mock to implement
16
* @param relaxUnitFun If true, only Unit-returning methods are relaxed
17
* @param mockValidator Validator for mockable classes (default: MockkValidator)
18
* @param block Initialization block executed after mock creation
19
* @return Mock instance of type T
20
*/
21
inline fun <reified T : Any> mockk(
22
name: String? = null,
23
relaxed: Boolean = false,
24
vararg moreInterfaces: KClass<*>,
25
relaxUnitFun: Boolean = false,
26
mockValidator: MockkValidator = MockkValidator(RestrictMockkConfiguration()),
27
block: T.() -> Unit = {}
28
): T
29
```
30
31
**Usage Examples:**
32
33
```kotlin
34
// Basic mock
35
val userService = mockk<UserService>()
36
37
// Named mock for debugging
38
val namedMock = mockk<UserService>(name = "TestUserService")
39
40
// Relaxed mock - unstubbed methods return defaults
41
val relaxedMock = mockk<UserService>(relaxed = true)
42
43
// Mock with additional interfaces
44
val multiInterfaceMock = mockk<UserService>(
45
moreInterfaces = arrayOf(Serializable::class, Cloneable::class)
46
)
47
48
// Mock with initialization block
49
val initializedMock = mockk<UserService> {
50
// Setup code here
51
}
52
```
53
54
### Spy Creation
55
56
Creates a spy that enables a mix of mocked behavior and real behavior.
57
58
```kotlin { .api }
59
/**
60
* Creates a spy using the default constructor
61
* @param name Optional name for the spy
62
* @param moreInterfaces Additional interfaces for the spy to implement
63
* @param recordPrivateCalls If true, enables verification of private method calls
64
* @param block Initialization block executed after spy creation
65
* @return Spy instance of type T
66
*/
67
inline fun <reified T : Any> spyk(
68
name: String? = null,
69
vararg moreInterfaces: KClass<*>,
70
recordPrivateCalls: Boolean = false,
71
block: T.() -> Unit = {}
72
): T
73
74
/**
75
* Creates a spy by copying from an existing object
76
* @param objToCopy Existing object to copy field values from
77
* @param name Optional name for the spy
78
* @param moreInterfaces Additional interfaces for the spy to implement
79
* @param recordPrivateCalls If true, enables verification of private method calls
80
* @param block Initialization block executed after spy creation
81
* @return Spy instance of type T
82
*/
83
inline fun <reified T : Any> spyk(
84
objToCopy: T,
85
name: String? = null,
86
vararg moreInterfaces: KClass<*>,
87
recordPrivateCalls: Boolean = false,
88
block: T.() -> Unit = {}
89
): T
90
```
91
92
**Usage Examples:**
93
94
```kotlin
95
// Spy with default constructor
96
val userSpy = spyk<UserService>()
97
98
// Spy from existing object
99
val existingUser = UserService("config")
100
val userSpyFromObject = spyk(existingUser)
101
102
// Spy with private call recording
103
val recordingSpyService = spyk<UserService>(recordPrivateCalls = true)
104
105
// Spy with initialization
106
val initializedSpy = spyk<UserService> {
107
// Partial stubbing - some methods mocked, others call original
108
}
109
```
110
111
### Mock from KClass
112
113
Creates a mock using explicit KClass instead of reified generics.
114
115
```kotlin { .api }
116
/**
117
* Creates a mock for an arbitrary class using KClass
118
* @param type The KClass of the type to mock
119
* @param name Optional name for the mock
120
* @param relaxed If true, unstubbed methods return default values
121
* @param moreInterfaces Additional interfaces for the mock to implement
122
* @param relaxUnitFun If true, only Unit-returning methods are relaxed
123
* @param block Initialization block executed after mock creation
124
* @return Mock instance of type T
125
*/
126
inline fun <T : Any> mockkClass(
127
type: KClass<T>,
128
name: String? = null,
129
relaxed: Boolean = false,
130
vararg moreInterfaces: KClass<*>,
131
relaxUnitFun: Boolean = false,
132
block: T.() -> Unit = {}
133
): T
134
```
135
136
**Usage Examples:**
137
138
```kotlin
139
// Mock using KClass when type inference isn't available
140
val serviceClass: KClass<UserService> = UserService::class
141
val service = mockkClass(serviceClass)
142
143
// In generic contexts
144
fun <T : Any> createMockOfType(clazz: KClass<T>): T {
145
return mockkClass(clazz, relaxed = true)
146
}
147
```
148
149
### Mock Type Checking
150
151
Utility function to check if an object is a MockK mock.
152
153
```kotlin { .api }
154
/**
155
* Checks if the provided object is a MockK mock of a certain type
156
* @param mock Object to check
157
* @param regular Check for regular mock (default: true)
158
* @param spy Check for spy (default: false)
159
* @param objectMock Check for object mock (default: false)
160
* @param staticMock Check for static mock (default: false)
161
* @param constructorMock Check for constructor mock (default: false)
162
* @return true if the object matches the specified mock types
163
*/
164
fun isMockKMock(
165
mock: Any,
166
regular: Boolean = true,
167
spy: Boolean = false,
168
objectMock: Boolean = false,
169
staticMock: Boolean = false,
170
constructorMock: Boolean = false
171
): Boolean
172
```
173
174
**Usage Examples:**
175
176
```kotlin
177
val mock = mockk<UserService>()
178
val spy = spyk<UserService>()
179
180
// Check if object is any kind of MockK mock
181
val isMock = isMockKMock(mock) // true
182
183
// Check specific mock types
184
val isSpy = isMockKMock(spy, regular = false, spy = true) // true
185
val isRegularMock = isMockKMock(mock, regular = true) // true
186
```
187
188
## Mock Configuration
189
190
### Relaxed Mocking
191
192
Relaxed mocks return default values for unstubbed methods instead of throwing exceptions.
193
194
```kotlin
195
// Fully relaxed - all unstubbed methods return defaults
196
val relaxedMock = mockk<UserService>(relaxed = true)
197
198
// Unit function relaxed - only Unit-returning methods are relaxed
199
val unitRelaxedMock = mockk<UserService>(relaxUnitFun = true)
200
```
201
202
### Additional Interfaces
203
204
Mocks can implement additional interfaces beyond their primary type.
205
206
```kotlin
207
interface Auditable {
208
fun audit(): String
209
}
210
211
val auditableMock = mockk<UserService>(
212
moreInterfaces = arrayOf(Auditable::class)
213
)
214
215
// Mock now implements both UserService and Auditable
216
every { (auditableMock as Auditable).audit() } returns "audited"
217
```
218
219
### Mock Naming
220
221
Named mocks are useful for debugging and identifying mocks in test output.
222
223
```kotlin
224
val namedMock = mockk<UserService>(name = "TestUserService")
225
// Mock will be identified as "TestUserService" in error messages
226
```