OKHttp client mock

General

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

Additional

Language
Java
Version
v2.0.0 (Nov 17, 2023)
Created
Aug 7, 2017
Updated
Feb 5, 2024
Owner
Guillermo Mazzola (gmazzo)
Contributors
Emmanuel Rodriguez (potyl)
Adriel Café (adrielcafe)
Guillermo Mazzola (gmazzo)
dependabot[bot]
Dmytro Semenchenko (gospodima)
Edgar Müller (edgarmueller)
canthonyl
7
Activity
Badge
Generate
Download
Source code

okhttp-client-mock

A simple OKHttp client mock, using a programmable request interceptor

Import

On your build.gradle add:

dependencies {
    testImplementation 'com.github.gmazzo.okhttp.mock:mock-client:<version>'
}

Usage

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

val interceptor = MockInterceptor().apply {

    rule(get or post or put, url eq "https://testserver/api/login") {
        respond(HTTP_401_UNAUTHORIZED).header("WWW-Authenticate", "Basic")
    }

    rule(url eq "https://testserver/api/json") {
        respond("{succeed:true}", MEDIATYPE_JSON)
    }

    rule(url eq "https://testserver/api/json") {
        respond(resource("sample.json"), MEDIATYPE_JSON)
    }

    rule(path matches "/aPath/(\\w+)".toRegex(), times = anyTimes) {
        respond { body("Path was " + it.url().encodedPath()) }
    }

    rule(delete) {
        respond(code = HTTP_405_METHOD_NOT_ALLOWED) {
            body("{succeed:false}", MEDIATYPE_JSON)
        }
    }

    // throw an exception
    rule(get) {
        respond { throw IllegalStateException("an IO error") }
    }

}

Or in Java:

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
  • 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