0
# MockWebServer
1
2
MockWebServer is a scriptable web server for testing HTTP clients. It allows developers to create lightweight mock servers for unit testing HTTP interactions by enqueueing predefined responses and verifying the requests made by client code. The library supports HTTP/1.1, HTTP/2, WebSockets, and SSL/TLS protocols with comprehensive testing capabilities.
3
4
## Package Information
5
6
- **Package Name**: com.squareup.okhttp3:mockwebserver
7
- **Package Type**: maven
8
- **Language**: Kotlin/Java
9
- **Installation**: Add to your build.gradle: `testImplementation 'com.squareup.okhttp3:mockwebserver:4.12.0'`
10
11
## Core Imports
12
13
```kotlin
14
import okhttp3.mockwebserver.MockWebServer
15
import okhttp3.mockwebserver.MockResponse
16
import okhttp3.mockwebserver.RecordedRequest
17
```
18
19
For Java:
20
21
```java
22
import okhttp3.mockwebserver.MockWebServer;
23
import okhttp3.mockwebserver.MockResponse;
24
import okhttp3.mockwebserver.RecordedRequest;
25
```
26
27
## Basic Usage
28
29
```kotlin
30
import okhttp3.mockwebserver.MockWebServer
31
import okhttp3.mockwebserver.MockResponse
32
33
// Create and start mock server
34
val server = MockWebServer()
35
server.enqueue(MockResponse().setBody("Hello, World!"))
36
server.start()
37
38
// Get server URL for client to connect to
39
val baseUrl = server.url("/")
40
41
// Your HTTP client makes request to baseUrl
42
// ...
43
44
// Verify the request that was made
45
val recordedRequest = server.takeRequest()
46
assertEquals("GET", recordedRequest.method)
47
assertEquals("/", recordedRequest.path)
48
49
// Clean up
50
server.shutdown()
51
```
52
53
## Architecture
54
55
MockWebServer is built around several key components:
56
57
- **MockWebServer**: The main server class that listens for connections and serves responses
58
- **MockResponse**: Scriptable response objects with headers, body, delays, and connection policies
59
- **RecordedRequest**: Immutable objects representing requests received by the server
60
- **Dispatcher**: Strategy pattern for determining which response to serve for each request
61
- **SocketPolicy**: Enum controlling connection lifecycle and failure simulation
62
63
## Capabilities
64
65
### Server Management
66
67
Core server functionality for starting, stopping, and configuring MockWebServer instances. Essential for all testing scenarios.
68
69
```kotlin { .api }
70
class MockWebServer : ExternalResource(), Closeable {
71
fun start(port: Int = 0)
72
fun start(inetAddress: InetAddress, port: Int)
73
fun shutdown()
74
fun close()
75
val port: Int
76
val hostName: String
77
fun url(path: String): HttpUrl
78
}
79
```
80
81
[Server Management](./server-management.md)
82
83
### Response Configuration
84
85
Comprehensive response building capabilities including headers, body content, delays, and connection policies. Supports both simple responses and complex scenarios like chunked encoding and HTTP/2 features.
86
87
```kotlin { .api }
88
class MockResponse : Cloneable {
89
fun setResponseCode(code: Int): MockResponse
90
fun setHeader(name: String, value: Any): MockResponse
91
fun setBody(body: String): MockResponse
92
fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse
93
fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit): MockResponse
94
fun setSocketPolicy(socketPolicy: SocketPolicy): MockResponse
95
}
96
```
97
98
[Response Configuration](./response-configuration.md)
99
100
### Request Verification
101
102
Request inspection and verification functionality for validating client behavior. Provides access to all request details including headers, body, and metadata.
103
104
```kotlin { .api }
105
class RecordedRequest {
106
val requestLine: String
107
val method: String?
108
val path: String?
109
val headers: Headers
110
val body: Buffer
111
val requestUrl: HttpUrl?
112
fun getHeader(name: String): String?
113
}
114
```
115
116
[Request Verification](./request-verification.md)
117
118
### Advanced Features
119
120
Advanced capabilities including custom dispatchers, HTTP/2 server push, duplex streaming, and SSL/TLS configuration.
121
122
```kotlin { .api }
123
abstract class Dispatcher {
124
abstract fun dispatch(request: RecordedRequest): MockResponse
125
}
126
127
class PushPromise(
128
val method: String,
129
val path: String,
130
val headers: Headers,
131
val response: MockResponse
132
)
133
```
134
135
[Advanced Features](./advanced-features.md)
136
137
## Types
138
139
```kotlin { .api }
140
enum class SocketPolicy {
141
SHUTDOWN_SERVER_AFTER_RESPONSE,
142
KEEP_OPEN,
143
DISCONNECT_AT_END,
144
UPGRADE_TO_SSL_AT_END,
145
DISCONNECT_AT_START,
146
DISCONNECT_AFTER_REQUEST,
147
DISCONNECT_DURING_REQUEST_BODY,
148
DISCONNECT_DURING_RESPONSE_BODY,
149
DO_NOT_READ_REQUEST_BODY,
150
FAIL_HANDSHAKE,
151
SHUTDOWN_INPUT_AT_END,
152
SHUTDOWN_OUTPUT_AT_END,
153
STALL_SOCKET_AT_START,
154
NO_RESPONSE,
155
RESET_STREAM_AT_START,
156
EXPECT_CONTINUE,
157
CONTINUE_ALWAYS
158
}
159
```