Coder Social home page Coder Social logo

okhttp-client-mock's Introduction

okhttp-client-mock

A simple OKHttp client mock, using a programmable request interceptor

Maven Central Build Status codecov Users

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

okhttp-client-mock's People

Contributors

adrielcafe avatar canthonyl avatar dependabot[bot] avatar edgarmueller avatar gmazzo avatar gospodima avatar potyl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

okhttp-client-mock's Issues

Documentation issues

Is the Java use case response (http_401_unauthorized) in the readme document extra parentheses?

Failed to match rule with specific URL

Hi,

I'm using this lib to replace some mocking code and wanted to add a rule for GET requests to a specific URL - basically the "Hello World" example:

https://github.com/MovingBlocks/TerasologyLauncher/blob/91d2056e11cf7cb6bd63474ffecc035e284d47ce/src/test/java/org/terasology/launcher/repositories/JenkinsClientTest.java#L58-L68

        final var interceptor = new MockInterceptor();
        interceptor.addRule()
                //TODO: I'd like to specify the URL here, but then matcher does not match.
                //      Somehow, the matcher surrounds the expected URL with some weird characters.
                //      expected=\Qhttps://jenkins.example\E;actual=https://jenkins.example/; matcher=url(~=\Qhttps://jenkins.example\E)
                .get()
                .respond("{ this is ] no json |[!");

        final var httpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

However, I see a matching exception which I don't understand:

java.lang.AssertionError: Not matched next rule: [method(GET), url(~=\Qhttps://jenkins.example\E)], consumed=false, request=Request{method=GET, url=https://jenkins.example/}
Failed to match:
	1: expected=\Qhttps://jenkins.example\E;actual=https://jenkins.example/; matcher=url(~=\Qhttps://jenkins.example\E)
	at okhttp3.mock.MockInterceptor.intercept(MockInterceptor.java:129)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
	at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
	at org.terasology.launcher.repositories.JenkinsClient.request(JenkinsClient.java:66)

Where do the surrounding \Q and \E come from? What am I missing here?

Throw exception

Hi there,

I would like to throw an exception when httpClient.newCall(request).execute() runs as part of my unit tests. How can I do this with your mock?

Cheers,
Olga

MockInterceptor rules - matches request body

hi All, when adding rules to MockInterceptor for returning a different response based on the request body for a post request, I was hoping to do something like this:

interceptor.addRule().post(url).requestBody(json1).anyTimes().respond(respondJson1); interceptor.addRule().post(url).requestBody(json2)..anyTimes().respond(respondJson2);

Is this something that can be added to the repo?
I can try open a PR

Java 8

Hi there,

What version can I use with java 8?

I keep getting this error:
bad class file: /home/runner/.m2/repository/com/github/gmazzo/okhttp-mock/1.4.0/okhttp-mock-1.4.0.jar(okhttp3/mock/MockInterceptor.class) class file has wrong version 55.0, should be 52.0 Please remove or make sure it appears in the correct subdirectory of the classpath.

Thanks,
Olga

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.