A simple OKHttp client mock, using a programmable request interceptor
On your build.gradle
add:
dependencies {
testCompile 'com.github.gmazzo:okhttp-mock:1.0.3'
}
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 classpathAndroidResources.asset
to load content from an Android's assetAndroidResources.rawRes
to load content from an Android's raw resourceRoboResources.asset
andRoboResources.rawRes
if you are running Roboelectric tests