• Stars
    star
    115
  • Rank 305,916 (Top 7 %)
  • Language
    Java
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple OKHttp client mock, using a programmable request interceptor

okhttp-client-mock

A simple OKHttp client mock, using a programmable request interceptor

Download Build Status codecov

Import

On your build.gradle add:

dependencies {
    testImplementation 'com.github.gmazzo:okhttp-mock:<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

More Repositories

1

gradle-buildconfig-plugin

A plugin for generating BuildConstants for any kind of Gradle projects: Java, Kotlin, Groovy, etc. Designed for KTS scripts.
Kotlin
468
star
2

gradle-android-test-aggregation-plugin

A couple Gradle plugins to make Android modules to work with JaCoCo Report Aggregation Plugin and Test Report Aggregation Plugin
Kotlin
30
star
3

gocd-build-watcher-plugin

A GoCD notification plugin which sends direct emails and Slack messages to the person who breaks a build
Java
8
star
4

android-nestedscroll-maps

Nested scroll (CoordinatorLayout, AppBarLayout and CollapsingToolbarLayout) support for Google Maps fragments
Java
6
star
5

gradle-apklib-plugin

An Android-Gradle plugin for generate DEX classes and a APK from a Library module.
Kotlin
5
star
6

gradle-play-autoincrement-plugin

An Android-Gradle plugin to set the build version based on the last APK uploaded on PlayStore
Groovy
3
star
7

gradle-wsdl-plugin

A Gradle plugin for generate JAB-WS clients from given WSDL files and URLs.
Groovy
2
star
8

java-techtalk

Java
2
star
9

android-parallel-intent-service

A multithreaded IntentService which can process requests in parallel and potentially keep multiple working queues.
Java
2
star
10

gs.kotlin.extensions.demo

Java
2
star
11

android-fontawesome

An Android library port of https://github.com/FortAwesome/Font-Awesome
Groovy
2
star
12

gradle-sqlite-plugin

A Gradle plugin to allow manipulating SQLite databases in the buildScript
Groovy
2
star
13

gradle-jerseywadl-plugin

A gradle plugin to generate Jersey 1.x client libreary from a given WADL or event from a Jersey 1.x web project directly.
Groovy
1
star
14

dnla-poc

A DNLA Android PoC using Cling library
Java
1
star
15

gradle-codeowners-plugin

A Gradle plugin to propagate CODEOWNERS after compiling JVM classes
Kotlin
1
star
16

android-unicorn

A funny Unicorn widget to include in your layouts as a gadget
Java
1
star