OKHttp client mock

General

Category
Free
Tag
HTTP Mocking
License
MIT License
Min SDK
1 (Android 1.0)
Registered
Feb 17, 2018
Favorites
0
Link
https://github.com/gmazzo/okhttp-client-mock
See also
OffIt
MockHttpServer
OkResponseFaker
Fixd
mockwebserver +

Additional

Language
Java
Version
N/A
Created
Aug 7, 2017
Updated
Feb 20, 2018
Owner
Guillermo Mazzola (gmazzo)
Contributor
Guillermo Mazzola (gmazzo)
1
Activity
Badge
Generate
Download
Source code

Advertising

okhttp-client-mock

A simple OKHttp client mock, using a programmable request interceptor

Import

On your build.gradle add:

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

Usage

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

MockInterceptor interceptor = new MockInterceptor();

interceptor.addRule(new Rule.Builder()
        .get().or().post().or().put()
        .url("https://testserver/api/login")
        .respond(HTTP_401_UNAUTHORIZED))
        .header("WWW-Authenticate", "Basic");

interceptor.addRule(new Rule.Builder()
        .get()
        .url("https://testserver/api/json")
        .respond("{succeed:true}", MEDIATYPE_JSON));

interceptor.addRule(new Rule.Builder()
        .get()
        .url("https://testserver/api/json")
        .respond(resource("sample.json"), MEDIATYPE_JSON));

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

OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

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