okhttp-mocker
is a Java Testing library to provide fake
responses for an OkHttp client.
Table of Contents:
<dependency>
<groupId>com.niklasarndt</groupId>
<artifactId>okhttp-mocker</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
Please make sure that the version number is up to date (via the badge at the top)!
Copy of the original usage notice:
Example code:
MockInterceptor interceptor = new MockInterceptor();
interceptor.addRule()
.get().or().post().or().put()
.url("https://testserver/api/login")
.respond(HTTP_401_UNAUTHORIZED))
.header("WWW-Authenticate", "Basic");
interceptor.addRule()
.get("https://testserver/api/json")
.respond("{succeed:true}", MEDIATYPE_JSON);
interceptor.addRule()
.get("https://testserver/api/json")
.respond(resource("sample.json"), MEDIATYPE_JSON);
interceptor.addRule()
.pathMatches(Pattern.compile("/aPath/(\\w+)"))
.anyTimes()
.answer(request -> new Response.Builder()
.code(200)
.body(ResponseBody.create(null, "Path was " + request.url().encodedPath())));
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
I didn't write most of the project's code myself, much of it is from gmazzo. It has been published under the MIT License and I'm therefore allowed to modify and extend it as long as I mention its origin.
The problems I faced were these:
- The project targeted at Android users. This is not a focus anymore (which means that integrations like Roboelectric have been removed). However, the code might work just fine on Android devices, even though I didn't (and won't) test this.
- The project was no longer maintained. I updated the dependencies and make sure all deprecations have been fixed.
- The project was not available at Maven Central, only via Jitpack. I wanted to simplify the setup process and therefore put it on Maven Central.
Testing only:
© Niklas Arndt 2021, MIT License
Much inspiration (and code) was taken from okhttp-client-mock. Since this repo seems to be inactive and isn't available from Maven Central, I decided to publish my own version.
You can find their original License here (MIT).