Home | History | Annotate | Download | only in mockwebserver
      1 MockWebServer
      2 =============
      3 
      4 A scriptable web server for testing HTTP clients
      5 
      6 
      7 ### Motivation
      8 
      9 This library makes it easy to test that your app Does The Right Thing when it
     10 makes HTTP and HTTPS calls. It lets you specify which responses to return and
     11 then verify that requests were made as expected.
     12 
     13 Because it exercises your full HTTP stack, you can be confident that you're
     14 testing everything. You can even copy & paste HTTP responses from your real web
     15 server to create representative test cases. Or test that your code survives in
     16 awkward-to-reproduce situations like 500 errors or slow-loading responses.
     17 
     18 
     19 ### Example
     20 
     21 Use MockWebServer the same way that you use mocking frameworks like
     22 [Mockito](https://code.google.com/p/mockito/):
     23 
     24 1. Script the mocks.
     25 2. Run application code.
     26 3. Verify that the expected requests were made.
     27 
     28 Here's a complete example:
     29 
     30 ```
     31   public 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.play();
     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 
     77 Your unit tests might move the `server` into a field so you can shut it down
     78 from your test's `tearDown()`.
     79 
     80 ### API
     81 
     82 #### MockResponse
     83 
     84 Mock responses default to an empty response body and a `200` status code.
     85 You can set a custom body with a string, input stream or byte array. Also
     86 add headers with a fluent builder API.
     87 
     88 ```
     89     MockResponse response = new MockResponse()
     90         .addHeader("Content-Type", "application/json; charset=utf-8")
     91         .addHeader("Cache-Control", "no-cache")
     92         .setBody("{}");
     93 ```
     94 
     95 MockResponse can be used to simulate a slow network. This is useful for
     96 testing timeouts and interactive testing.
     97 
     98 ```
     99     response.throttleBody(1024, 1, TimeUnit.SECONDS);
    100 ```
    101 
    102 
    103 #### RecordedRequest
    104 
    105 Verify requests by their method, path, HTTP version, body, and headers.
    106 
    107 ```
    108     RecordedRequest request = server.takeRequest();
    109     assertEquals("POST /v1/chat/send HTTP/1.1", request.getRequestLine());
    110     assertEquals("application/json; charset=utf-8", request.getHeader("Content-Type"));
    111     assertEquals("{}", request.getUtf8Body());
    112 ```
    113 
    114 #### Dispatcher
    115 
    116 By default MockWebServer uses a queue to specify a series of responses. Use a
    117 Dispatcher to handle requests using another policy. One natural policy is to
    118 dispatch on the request path.
    119 
    120 
    121 ### Download
    122 
    123 The best way to get MockWebServer is via Maven:
    124 
    125 ```
    126 <dependency>
    127   <groupId>com.squareup.okhttp</groupId>
    128   <artifactId>mockwebserver</artifactId>
    129   <version>(insert latest version)</version>
    130   <scope>test</scope>
    131 </dependency>
    132 ```
    133 
    134 ### License
    135 
    136     Licensed under the Apache License, Version 2.0 (the "License");
    137     you may not use this file except in compliance with the License.
    138     You may obtain a copy of the License at
    139 
    140        http://www.apache.org/licenses/LICENSE-2.0
    141 
    142     Unless required by applicable law or agreed to in writing, software
    143     distributed under the License is distributed on an "AS IS" BASIS,
    144     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    145     See the License for the specific language governing permissions and
    146     limitations under the License.
    147