/ Miscellaneous

A simple OKHttp client mock using a programmable request interceptor


A simple OKHttp client mock, using a programmable request interceptor


On your build.gradle add:

dependencies {
    testCompile 'com.github.gmazzo:okhttp-mock:1.0.4'


Create an OkHttp request interceptor and record some rules, for example:

MockInterceptor interceptor = new MockInterceptor();

interceptor.addRule(new Rule.Builder()
        .header("WWW-Authenticate", "Basic");

interceptor.addRule(new Rule.Builder()
        .respond("{succeed:true}", MEDIATYPE_JSON));

interceptor.addRule(new Rule.Builder()
        .respond(resource("sample.json"), MEDIATYPE_JSON));

Then add the interceptor to your OkHttpClient client and use it as usual:

OkHttpClient client = new OkHttpClient.Builder()

Check an example Integration Test with mocked HTTP responses

You can use the following helper classes to provide mock responses from resources:

  • ClasspathResources.resource to load content from classpath
  • AndroidResources.asset to load content from an Android's asset
  • AndroidResources.rawRes to load content from an Android's raw resource
  • RoboResources.asset and RoboResources.rawRes if you are running Roboelectric tests