• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1MockWebServer
2=============
3
4A scriptable web server for testing HTTP clients
5
6
7### Motivation
8
9This library makes it easy to test that your app Does The Right Thing when it
10makes HTTP and HTTPS calls. It lets you specify which responses to return and
11then verify that requests were made as expected.
12
13Because it exercises your full HTTP stack, you can be confident that you're
14testing everything. You can even copy & paste HTTP responses from your real web
15server to create representative test cases. Or test that your code survives in
16awkward-to-reproduce situations like 500 errors or slow-loading responses.
17
18
19### Example
20
21Use MockWebServer the same way that you use mocking frameworks like
22[Mockito](https://code.google.com/p/mockito/):
23
241. Script the mocks.
252. Run application code.
263. Verify that the expected requests were made.
27
28Here's a complete example:
29
30```java
31public void test() throws Exception {
32  // Create a MockWebServer. These are lean enough that you can create a new
33  // instance for every unit test.
34  MockWebServer server = new MockWebServer();
35
36  // Schedule some responses.
37  server.enqueue(new MockResponse().setBody("hello, world!"));
38  server.enqueue(new MockResponse().setBody("sup, bra?"));
39  server.enqueue(new MockResponse().setBody("yo dog"));
40
41  // Start the server.
42  server.start();
43
44  // Ask the server for its URL. You'll need this to make HTTP requests.
45  HttpUrl baseUrl = server.url("/v1/chat/");
46
47  // Exercise your application code, which should make those HTTP requests.
48  // Responses are returned in the same order that they are enqueued.
49  Chat chat = new Chat(baseUrl);
50
51  chat.loadMore();
52  assertEquals("hello, world!", chat.messages());
53
54  chat.loadMore();
55  chat.loadMore();
56  assertEquals(""
57      + "hello, world!\n"
58      + "sup, bra?\n"
59      + "yo dog", chat.messages());
60
61  // Optional: confirm that your app made the HTTP requests you were expecting.
62  RecordedRequest request1 = server.takeRequest();
63  assertEquals("/v1/chat/messages/", request1.getPath());
64  assertNotNull(request1.getHeader("Authorization"));
65
66  RecordedRequest request2 = server.takeRequest();
67  assertEquals("/v1/chat/messages/2", request2.getPath());
68
69  RecordedRequest request3 = server.takeRequest();
70  assertEquals("/v1/chat/messages/3", request3.getPath());
71
72  // Shut down the server. Instances cannot be reused.
73  server.shutdown();
74}
75```
76
77Your unit tests might move the `server` into a field so you can shut it down
78from your test's `tearDown()`.
79
80### API
81
82#### MockResponse
83
84Mock responses default to an empty response body and a `200` status code.
85You can set a custom body with a string, input stream or byte array. Also
86add headers with a fluent builder API.
87
88```java
89MockResponse response = new MockResponse()
90    .addHeader("Content-Type", "application/json; charset=utf-8")
91    .addHeader("Cache-Control", "no-cache")
92    .setBody("{}");
93```
94
95MockResponse can be used to simulate a slow network. This is useful for
96testing timeouts and interactive testing.
97
98```java
99response.throttleBody(1024, 1, TimeUnit.SECONDS);
100```
101
102
103#### RecordedRequest
104
105Verify requests by their method, path, HTTP version, body, and headers.
106
107```java
108RecordedRequest request = server.takeRequest();
109assertEquals("POST /v1/chat/send HTTP/1.1", request.getRequestLine());
110assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type"));
111assertEquals("{}", request.getUtf8Body());
112```
113
114#### Dispatcher
115
116By default MockWebServer uses a queue to specify a series of responses. Use a
117Dispatcher to handle requests using another policy. One natural policy is to
118dispatch on the request path.
119You can, for example, filter the request instead of using `server.enqueue()`.
120
121```java
122final Dispatcher dispatcher = new Dispatcher() {
123
124    @Override
125    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
126
127        if (request.getPath().equals("/v1/login/auth/")){
128            return new MockResponse().setResponseCode(200);
129        } else if (request.getPath().equals("v1/check/version/")){
130            return new MockResponse().setResponseCode(200).setBody("version=9");
131        } else if (request.getPath().equals("/v1/profile/info")) {
132            return new MockResponse().setResponseCode(200).setBody("{\\\"info\\\":{\\\"name\":\"Lucas Albuquerque\",\"age\":\"21\",\"gender\":\"male\"}}");
133        }
134        return new MockResponse().setResponseCode(404);
135    }
136};
137server.setDispatcher(dispatcher);
138```
139
140
141### Download
142
143Get MockWebServer via Maven:
144```xml
145<dependency>
146  <groupId>com.squareup.okhttp</groupId>
147  <artifactId>mockwebserver</artifactId>
148  <version>(insert latest version)</version>
149  <scope>test</scope>
150</dependency>
151```
152
153or via Gradle
154```groovy
155testCompile 'com.squareup.okhttp:mockwebserver:(insert latest version)'
156```
157
158### License
159
160    Licensed under the Apache License, Version 2.0 (the "License");
161    you may not use this file except in compliance with the License.
162    You may obtain a copy of the License at
163
164       http://www.apache.org/licenses/LICENSE-2.0
165
166    Unless required by applicable law or agreed to in writing, software
167    distributed under the License is distributed on an "AS IS" BASIS,
168    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
169    See the License for the specific language governing permissions and
170    limitations under the License.
171