Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
}
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add it in your build.sbt at the end of resolvers:
resolvers += "jitpack" at "https://jitpack.io"
Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency
dependencies {
implementation 'com.github.filipebrandao:okhttp-client-mock:v0.1-charlie'
}
<dependency>
<groupId>com.github.filipebrandao</groupId>
<artifactId>okhttp-client-mock</artifactId>
<version>v0.1-charlie</version>
</dependency>
libraryDependencies += "com.github.filipebrandao" % "okhttp-client-mock" % "v0.1-charlie"
:dependencies [[com.github.filipebrandao/okhttp-client-mock "v0.1-charlie"]]
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
and RoboResources.rawRes
if you are running Roboelectric tests