OkHttp is a very powerful HTTP client for Java allowing you to consume RESTful or other resources easily.
In this example below we have a method that sends a request to a service to create a customer.
OkHttp is great as it separates the request from the HTTP call, allowing you flexibility on building a request and executing it.
The ability to build a request separately and then invoke it using the OkHttpClient is a great feature to allow flexibility for developers in their implementation approach.
Testing
The recommended way of testing your code that uses OkHttp is to utilise their MockWebServer utility. This allows the execution of tests in a realistic operation with full control of responses being passed to the client.
The OkHttpClient and Builder are not easy to test using a Mocking framework, which is in part due to its design. Powermock is possible to use as a workaround, however your mileage may vary.
It is very straightforward to setup a testing scenario using the MockWebServer.
In the test setup() method we start an instance of the MockWebServer and get the URL of it. This allows us to configure the HttpClient class, so it sends the requests to the correct location.
Next we create an instance of Jackson's ObjectMapper, so real request and response objects can be de/serialized to and from JSON.
Then we create an instance of the HttpClient we are going to write tests for.
Testing Good Requests and Responses
Building a test is no different than the structure of any other unit test.
The key point is to ensure the mockWebServer object is enqueued with a response for the given scenario. Otherwise no response will be provided when OkHttp makes a real request.
Testing Bad Responses
Testing IOException / Network Failures
The prior scenarios all cover situations where the server sends a positive or negative response. In the production environment this will not always be the case; where a network failure or a HTTP timeout could occur.
Testing these scenarios are straightforward using the MockWebServer's SocketPolicy property.
This second test is very useful to make sure you have configured your OkHttp client with a proper timeout value. Which is very important for requests that are made in a high volume. The last thing you need to is tie up precious JVM heap-space with multiple requests that are failing to timeout in a timely manner!
Conclusion
The MockWebServer is a great counterpart to OkHttpClient, and allows you to make realistic tests without the hassle of mocking.