0
# Mock Creation and Spying
1
2
Mockito provides several ways to create mock objects and spies for testing. Mocks are fake objects that record interactions, while spies are partial mocks that wrap real objects.
3
4
## Mock Creation
5
6
### Basic Mock Creation
7
8
Create a mock of any class or interface:
9
10
```java { .api }
11
public static <T> T mock(Class<T> classToMock);
12
```
13
14
**Usage Example:**
15
```java
16
List<String> mockedList = mock(List.class);
17
Map<String, Integer> mockedMap = mock(Map.class);
18
UserService mockedService = mock(UserService.class);
19
```
20
21
### Named Mocks
22
23
Create mocks with custom names for better debugging:
24
25
```java { .api }
26
public static <T> T mock(Class<T> classToMock, String name);
27
```
28
29
**Usage Example:**
30
```java
31
List<String> mockedList = mock(List.class, "userList");
32
// Error messages will show "userList" instead of generic mock name
33
```
34
35
### Mocks with Default Answers
36
37
Create mocks with predefined behavior for unstubbed methods:
38
39
```java { .api }
40
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer);
41
```
42
43
**Usage Example:**
44
```java
45
List<String> mockedList = mock(List.class, RETURNS_SMART_NULLS);
46
UserService service = mock(UserService.class, CALLS_REAL_METHODS);
47
```
48
49
### Mocks with Settings
50
51
Create mocks with advanced configuration options:
52
53
```java { .api }
54
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings);
55
```
56
57
**Usage Example:**
58
```java
59
UserService service = mock(UserService.class,
60
withSettings()
61
.name("userService")
62
.defaultAnswer(RETURNS_SMART_NULLS)
63
.extraInterfaces(Serializable.class)
64
.serializable());
65
```
66
67
### Deprecated Mock Creation
68
69
```java { .api }
70
@Deprecated
71
public static <T> T mock(Class<T> classToMock, ReturnValues returnValues);
72
```
73
74
## Spy Creation
75
76
### Spying on Objects
77
78
Create a spy that wraps a real object:
79
80
```java { .api }
81
public static <T> T spy(T object);
82
```
83
84
**Usage Example:**
85
```java
86
List<String> realList = new ArrayList<>();
87
List<String> spyList = spy(realList);
88
89
// Real method is called
90
spyList.add("item");
91
assertEquals(1, spyList.size());
92
93
// Can stub methods
94
when(spyList.size()).thenReturn(100);
95
assertEquals(100, spyList.size());
96
```
97
98
### Spying on Classes (v1.10.12+)
99
100
Create a spy of a class without providing an instance:
101
102
```java { .api }
103
public static <T> T spy(Class<T> classToSpy);
104
```
105
106
**Usage Example:**
107
```java
108
UserService spyService = spy(UserService.class);
109
// Mockito creates an instance using default constructor
110
```
111
112
## Mock Settings Builder
113
114
Configure advanced mock behavior:
115
116
```java { .api }
117
public static MockSettings withSettings();
118
119
public interface MockSettings {
120
MockSettings name(String name);
121
MockSettings defaultAnswer(Answer defaultAnswer);
122
MockSettings extraInterfaces(Class<?>... interfaces);
123
MockSettings serializable();
124
MockSettings verboseLogging();
125
MockSettings invocationListeners(InvocationListener... listeners);
126
MockSettings spiedInstance(Object spiedInstance);
127
}
128
```
129
130
**Usage Examples:**
131
132
```java
133
// Mock with multiple interfaces
134
Runnable mock = mock(Runnable.class,
135
withSettings().extraInterfaces(Serializable.class, Cloneable.class));
136
137
// Serializable mock
138
List<String> serializableMock = mock(List.class,
139
withSettings().serializable());
140
141
// Mock with verbose logging
142
UserService verboseService = mock(UserService.class,
143
withSettings().verboseLogging());
144
145
// Mock with custom default answer
146
Calculator calc = mock(Calculator.class,
147
withSettings().defaultAnswer(RETURNS_SMART_NULLS));
148
```
149
150
## Answer Strategies
151
152
Control how unstubbed methods behave:
153
154
```java { .api }
155
public static final Answer<Object> RETURNS_DEFAULTS;
156
public static final Answer<Object> RETURNS_SMART_NULLS;
157
public static final Answer<Object> RETURNS_MOCKS;
158
public static final Answer<Object> RETURNS_DEEP_STUBS;
159
public static final Answer<Object> CALLS_REAL_METHODS;
160
```
161
162
### RETURNS_DEFAULTS
163
- Returns null for objects, 0 for numbers, false for booleans
164
- Empty collections for Collection types
165
- Default behavior for mocks
166
167
### RETURNS_SMART_NULLS
168
- Returns SmartNull objects that provide helpful error messages
169
- Helps identify NullPointerException sources in tests
170
171
### RETURNS_MOCKS
172
- Returns mocks for non-primitive return types
173
- Useful for fluent interfaces and chaining
174
175
### RETURNS_DEEP_STUBS
176
- Automatically creates mock chains for method chaining
177
- Example: `mock.getFoo().getBar().getBaz()` works without explicit stubbing
178
179
### CALLS_REAL_METHODS
180
- Calls real methods on the mock
181
- Useful for partial mocking and spies
182
183
## Best Practices
184
185
### When to Use Mocks vs Spies
186
187
**Use Mocks when:**
188
- Testing interactions with dependencies
189
- Need complete control over behavior
190
- Working with interfaces or abstract classes
191
- Don't want real code execution
192
193
**Use Spies when:**
194
- Need partial mocking of real objects
195
- Want most methods to behave normally
196
- Testing legacy code with limited refactoring options
197
- Need to verify calls on real objects
198
199
### Spy Gotchas
200
201
```java
202
// WRONG - real method is called during stubbing
203
List<String> spy = spy(new ArrayList<>());
204
when(spy.get(0)).thenReturn("foo"); // IndexOutOfBoundsException!
205
206
// CORRECT - use doReturn family for spies
207
doReturn("foo").when(spy).get(0);
208
```
209
210
### Mock Configuration Tips
211
212
```java
213
// Good - descriptive names for debugging
214
UserService userService = mock(UserService.class, "userService");
215
216
// Good - appropriate default answers
217
HttpClient client = mock(HttpClient.class, RETURNS_SMART_NULLS);
218
219
// Good - extra interfaces when needed
220
Runnable task = mock(Runnable.class,
221
withSettings().extraInterfaces(Serializable.class));
222
```