• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

src/22-Nov-2023-2,4321,642

README.mdD22-Nov-20235.2 KiB167121

pom.xmlD22-Nov-20232.2 KiB7569

README.md

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  URL baseUrl = server.getUrl("/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
143The best way to get MockWebServer is via Maven:
144
145```xml
146<dependency>
147  <groupId>com.squareup.okhttp</groupId>
148  <artifactId>mockwebserver</artifactId>
149  <version>(insert latest version)</version>
150  <scope>test</scope>
151</dependency>
152```
153
154### License
155
156    Licensed under the Apache License, Version 2.0 (the "License");
157    you may not use this file except in compliance with the License.
158    You may obtain a copy of the License at
159
160       http://www.apache.org/licenses/LICENSE-2.0
161
162    Unless required by applicable law or agreed to in writing, software
163    distributed under the License is distributed on an "AS IS" BASIS,
164    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
165    See the License for the specific language governing permissions and
166    limitations under the License.
167