0
# Retrofit Mock
1
2
Retrofit Mock is a Java library that provides mock web server functionality for testing HTTP responses and simulating network behavior with Retrofit. It enables developers to create controllable, deterministic network simulations without requiring actual network connections, making it ideal for unit testing HTTP-based applications.
3
4
## Package Information
5
6
- **Package Name**: retrofit-mock
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>com.squareup.retrofit2</groupId>
13
<artifactId>retrofit-mock</artifactId>
14
<version>3.0.0</version>
15
</dependency>
16
```
17
18
Gradle:
19
```gradle
20
implementation 'com.squareup.retrofit2:retrofit-mock:3.0.0'
21
```
22
23
## Core Imports
24
25
```java
26
import retrofit2.mock.MockRetrofit;
27
import retrofit2.mock.NetworkBehavior;
28
import retrofit2.mock.BehaviorDelegate;
29
import retrofit2.mock.Calls;
30
```
31
32
## Basic Usage
33
34
```java
35
import retrofit2.Retrofit;
36
import retrofit2.mock.MockRetrofit;
37
import retrofit2.mock.NetworkBehavior;
38
import retrofit2.mock.BehaviorDelegate;
39
import retrofit2.mock.Calls;
40
41
// Create a Retrofit instance
42
Retrofit retrofit = new Retrofit.Builder()
43
.baseUrl("http://example.com")
44
.build();
45
46
// Create network behavior with simulated delays and failures
47
NetworkBehavior behavior = NetworkBehavior.create();
48
behavior.setDelay(1000, TimeUnit.MILLISECONDS);
49
behavior.setFailurePercent(10); // 10% failure rate
50
51
// Create MockRetrofit instance
52
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
53
.networkBehavior(behavior)
54
.build();
55
56
// Create a mock service delegate
57
BehaviorDelegate<MyService> delegate = mockRetrofit.create(MyService.class);
58
59
// Create a mock implementation
60
MyService mockService = delegate.returningResponse("Hello World");
61
```
62
63
## Architecture
64
65
The Retrofit Mock library consists of four main components:
66
67
1. **MockRetrofit**: The primary entry point that coordinates mock behavior
68
2. **NetworkBehavior**: Configures network simulation parameters (delays, failures, errors)
69
3. **BehaviorDelegate**: Creates mock service implementations with applied network behavior
70
4. **Calls**: Utility class for creating immediate response or failure Call instances
71
72
## Capabilities
73
74
### Mock Retrofit Creation
75
76
Create MockRetrofit instances to coordinate mock behavior with real Retrofit configurations.
77
78
```java { .api }
79
public final class MockRetrofit {
80
public Retrofit retrofit();
81
public NetworkBehavior networkBehavior();
82
public Executor backgroundExecutor();
83
public <T> BehaviorDelegate<T> create(Class<T> service);
84
}
85
```
86
87
```java { .api }
88
public static final class MockRetrofit.Builder {
89
public Builder(Retrofit retrofit);
90
public Builder networkBehavior(NetworkBehavior behavior);
91
public Builder backgroundExecutor(ExecutorService executor);
92
public MockRetrofit build();
93
}
94
```
95
96
**Usage Example:**
97
```java
98
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
99
.networkBehavior(NetworkBehavior.create())
100
.backgroundExecutor(Executors.newSingleThreadExecutor())
101
.build();
102
```
103
104
### Network Behavior Simulation
105
106
Configure realistic network conditions including delays, variance, and failure rates.
107
108
```java { .api }
109
public final class NetworkBehavior {
110
public static NetworkBehavior create();
111
public static NetworkBehavior create(Random random);
112
113
// Delay configuration
114
public void setDelay(long amount, TimeUnit unit);
115
public long delay(TimeUnit unit);
116
117
// Variance configuration
118
public void setVariancePercent(int variancePercent);
119
public int variancePercent();
120
121
// Failure configuration
122
public void setFailurePercent(int failurePercent);
123
public int failurePercent();
124
public void setFailureException(Throwable exception);
125
public Throwable failureException();
126
127
// Error response configuration
128
public int errorPercent();
129
public void setErrorPercent(int errorPercent);
130
public void setErrorFactory(Callable<Response<?>> errorFactory);
131
public Response<?> createErrorResponse();
132
133
// Behavior calculation
134
public boolean calculateIsFailure();
135
public boolean calculateIsError();
136
public long calculateDelay(TimeUnit unit);
137
}
138
```
139
140
**Default Configuration:**
141
- Delay: 2000ms
142
- Variance: 40%
143
- Failure rate: 3%
144
- Error rate: 0%
145
146
**Usage Example:**
147
```java
148
NetworkBehavior behavior = NetworkBehavior.create();
149
behavior.setDelay(500, TimeUnit.MILLISECONDS);
150
behavior.setVariancePercent(20);
151
behavior.setFailurePercent(5);
152
behavior.setErrorPercent(10);
153
```
154
155
### Service Mock Implementation
156
157
Create mock implementations of Retrofit service interfaces with applied network behavior.
158
159
```java { .api }
160
public final class BehaviorDelegate<T> {
161
public T returningResponse(@Nullable Object response);
162
public <R> T returning(Call<R> call);
163
}
164
```
165
166
**Usage Example:**
167
```java
168
// Define your service interface
169
interface ApiService {
170
@GET("/users")
171
Call<List<User>> getUsers();
172
}
173
174
// Create delegate and mock implementation
175
BehaviorDelegate<ApiService> delegate = mockRetrofit.create(ApiService.class);
176
177
// Mock with simple response
178
ApiService mockService = delegate.returningResponse(Arrays.asList(
179
new User("John", "john@example.com"),
180
new User("Jane", "jane@example.com")
181
));
182
183
// Mock with custom Call behavior
184
ApiService mockService2 = delegate.returning(
185
Calls.response(Response.success(userList))
186
);
187
```
188
189
### Immediate Response Calls
190
191
Create Call instances that immediately respond with success or failure, useful for testing specific scenarios.
192
193
```java { .api }
194
public final class Calls {
195
public static <T> Call<T> defer(Callable<Call<T>> callable);
196
public static <T> Call<T> response(@Nullable T successValue);
197
public static <T> Call<T> response(Response<T> response);
198
public static <T> Call<T> failure(IOException failure);
199
public static <T> Call<T> failure(Throwable failure);
200
}
201
```
202
203
**Usage Examples:**
204
```java
205
// Immediate success response
206
Call<String> successCall = Calls.response("Success!");
207
208
// Immediate failure
209
Call<String> failureCall = Calls.failure(new IOException("Network error"));
210
211
// Custom response with metadata
212
Response<String> customResponse = Response.success("Data",
213
new okhttp3.ResponseBody.create(null, ""));
214
Call<String> customCall = Calls.response(customResponse);
215
216
// Deferred call that computes response when executed
217
Call<String> deferredCall = Calls.defer(() -> {
218
if (shouldSucceed()) {
219
return Calls.response("Success");
220
} else {
221
return Calls.failure(new IOException("Deferred failure"));
222
}
223
});
224
```
225
226
## Types
227
228
```java { .api }
229
// NetworkBehavior uses these standard Java types
230
import java.util.concurrent.TimeUnit;
231
import java.util.concurrent.Callable;
232
import java.util.Random;
233
234
// Retrofit and OkHttp types used throughout
235
import retrofit2.Call;
236
import retrofit2.Response;
237
import retrofit2.Retrofit;
238
import java.util.concurrent.ExecutorService;
239
import java.util.concurrent.Executor;
240
```
241
242
### Exception Types
243
244
```java { .api }
245
// Default exception thrown by network failures
246
final class MockRetrofitIOException extends IOException {
247
MockRetrofitIOException();
248
}
249
```
250
251
## Error Handling
252
253
The library handles errors through several mechanisms:
254
255
1. **Network Failures**: Configured via `setFailurePercent()` and `setFailureException()`
256
- Default: 3% failure rate with MockRetrofitIOException
257
- Failures throw the configured exception
258
259
2. **HTTP Errors**: Configured via `setErrorPercent()` and `setErrorFactory()`
260
- Default: 0% error rate with HTTP 500 response
261
- Errors return unsuccessful Response objects
262
263
3. **Immediate Failures**: Created via `Calls.failure()`
264
- Supports both IOException and general Throwable
265
- RuntimeException and Error types are thrown directly
266
267
**Error Configuration Example:**
268
```java
269
NetworkBehavior behavior = NetworkBehavior.create();
270
271
// Custom failure behavior
272
behavior.setFailurePercent(15);
273
IOException customException = new IOException("Custom network failure");
274
customException.setStackTrace(new StackTraceElement[0]); // Remove misleading stack trace
275
behavior.setFailureException(customException);
276
277
// Custom error responses
278
behavior.setErrorPercent(20);
279
behavior.setErrorFactory(() ->
280
Response.error(404, ResponseBody.create(null, "Not Found")));
281
```
282
283
## Advanced Usage
284
285
### Kotlin Coroutines Support
286
287
The library fully supports Retrofit's Kotlin suspend functions:
288
289
```kotlin
290
interface ApiService {
291
@GET("/users")
292
suspend fun getUsers(): List<User>
293
294
@GET("/user/{id}")
295
suspend fun getUser(@Path("id") id: String): Response<User>
296
}
297
298
// Mock implementation works seamlessly with suspend functions
299
val mockService = delegate.returningResponse(listOf(User("test")))
300
val users = mockService.getUsers() // Suspend function call
301
```
302
303
### Custom Executors
304
305
Control background execution with custom ExecutorService:
306
307
```java
308
ExecutorService customExecutor = Executors.newFixedThreadPool(2);
309
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
310
.backgroundExecutor(customExecutor)
311
.build();
312
```
313
314
### Testing Patterns
315
316
Common testing patterns with Retrofit Mock:
317
318
```java
319
@Test
320
public void testNetworkFailure() {
321
NetworkBehavior behavior = NetworkBehavior.create();
322
behavior.setFailurePercent(100); // Force failure
323
324
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
325
.networkBehavior(behavior)
326
.build();
327
328
ApiService service = mockRetrofit.create(ApiService.class)
329
.returningResponse("test");
330
331
// This call will fail due to 100% failure rate
332
Call<String> call = service.getData();
333
// ... test failure handling
334
}
335
336
@Test
337
public void testSlowNetwork() {
338
NetworkBehavior behavior = NetworkBehavior.create();
339
behavior.setDelay(5, TimeUnit.SECONDS);
340
behavior.setVariancePercent(50); // ±50% variance
341
342
// ... test timeout handling and slow network scenarios
343
}
344
```