Mock your datas for Okhttp and Retrofit in json format in just a few moves

Overview

okhttp-json-mock

Android Arsenal

This simple library helps you mock your data for using with okhttp+retrofit in json format in just a few moves. it forwards the requests to local json files and returns the data stored in them.

Version 3.0 Notes:

3.0 introduces breaking changes, since it removes the wrapper for mocked responses (MockedResponse.java) and therefor does not alter the api anymore. Data transfer objects are now accessed directly without embedding them into an additional json object. See the Version 2.0 Documentation for the old api.

Version 2.0 Notes:

Since version 2.0 the dependency to android platform is removed so it will be useful for all your jvm-based projects, not just android. You can still use version 1.1.1 if you don't care.

Usage

First add jitpack to your projects build.gradle file

allprojects {
   	repositories {
   		...
   		maven { url "https://jitpack.io" }
   	}
}

Then add the dependency in modules build.gradle file

dependencies {
    compile 'com.github.mirrajabi:okhttp-json-mock:3.0'
 }

Since version 2.0:

  1. Construct your custom InputStreamProvider:
InputStreamProvider inputStreamProvider = new InputStreamProvider() {
    @Override
    public InputStream provide(String path) {
        try {
            return getAssets().open(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
};
  1. Use the InputStreamProvider to construct the OkHttpMockInterceptor and client:
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new OkHttpMockInterceptor(getAndroidProvider(), 5))
    .build();

For version 1.+

1. Add OkhttpMockInterceptor to your OkhttpClient instance and attach it to your retrofit instance

OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new OkHttpMockInterceptor(this, 5))
    .build();
    
mRetrofit = new Retrofit.Builder()
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .baseUrl("http://example.com")
    .client(mOkHttpClient)
    .build();

2. Prepare your api service interfaces for retrofit

//usage example /users/page=phoneNumbers.json
@GET(API_VERSION + "/users")
Observable<ArrayList<UserModel>> getUsers(@Query("page") int page);

//usage example /users/page=1&secondParameter=phoneNumbers.json
@GET(API_VERSION + "/users")
Observable<ArrayList<UserModel>> getUsers(@Query("page") int page,
                                          @Query("name") String name);

//usage example /users/1.json
@GET(API_VERSION + "/users/{userId}")
Observable<UserModel> getUser(@Path("userId") int userId);

//usage example /users/1/phoneNumbers.json
@GET(API_VERSION + "/users/{userId}/phoneNumbers")
Observable<ArrayList<String>> getUserNumbers(@Path("userId") int userId);

3. Put your json models in assets folder like the examples

\---api
    \---v1
        \---users
            |   1.json
            |   2.json
            |   3.json
            |   page=1.json
            |
            +---1
            |       phoneNumbers.json
            |
            +---2
            |       phoneNumbers.json
            |
            \---3
                    phoneNumbers.json

Retrofit's annotations

Currently @Query and @Path can be achieved simply with correct folder and file namings (like website routes) for example if you have a request like

@GET("api/v1/posts/{userId}")
Observable<ArrayList<Post>> getUserPosts(@Path("userId"),
                                         @Query("page") int page,
                                         @Query("categoryId") int categoryId);

you can have json models in api/v1/posts/{userId} where {userId} could be an integer like api/v1/posts/3 and in that folder the json files should have names like page=1&categoryId=5.json so multiple queries are achievable by seperating them using Ampersand(&) character

You can take a look at Sample app for a working example

Contributions

Any contributions are welcome. just fork it and submit your changes to your fork and then create a pull request

Changelog

3.0 - Removed wrapper for mocked responses

2.0 - The library no longer depends on android classes

1.1.1 - Fixes file name lowercase issue

1.1 - Adds delay customization option.

Comments
  • This library has a dependency on Android

    This library has a dependency on Android

    This is not mentioned in the repo description anywhere, but it makes this library unsuitable for non-Android projects and tests, unless you want to use Robolectric.

    opened by maartenvang 5
  • HTTP FAILED: java.lang.IllegalStateException: message == null

    HTTP FAILED: java.lang.IllegalStateException: message == null

    Hi guys and thank you for this great lib !

    I'm currently using it for the first time and I have a small problem. Maybe it comes from a wrong usage of the lib.

    Concretely, I have :

    • a BASE_URL = "https://changeme.com"
    • a file hello.json located at assets/api which content is : { "hello": "test" }
    • a model class : data class Hello(val hello:String)
    • a retrofit service : interface HelloService { @GET("api/hello") fun getHello(): Single<Hello> }

    Here's how I create my retrofit instance including the mock interceptors on OkHttpClient :

               val httpClient = OkHttpClient.Builder()
    
               if (BuildConfig.DEBUG) 
                httpClient.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                
               if (inputStreamProvider != null)
                    httpClient.addInterceptor(OkHttpMockInterceptor(inputStreamProvider, 5))
    
                val retrofit = Retrofit.Builder()
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .baseUrl(baseUrl)
                        .client(httpClient.build())
                        .build()
    
    

    Finally, here's my inputStreamProvider instanciation :

    private val inputStreamProvider = InputStreamProvider {
            try {
                assets.open(it)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            null
        }
    

    The error I have when I use my service is that I haven't the response I expect and I have an error :

    D/OkHttp: --> GET https://changeme.com/api/hello
              --> END GET
    D/OkHttp: <-- HTTP FAILED: java.lang.IllegalStateException: message == null
    

    Has anyone an idea of the problem here ? It will be very useful !

    Thank you :+1: !

    opened by Aissa-H 3
  • Using library for testing

    Using library for testing

    Hi, I configured the library for requests in a common scenario (normal apk compilation) and works fine. I have a problem trying to use this library for mock requests for testing purposes. The problem is that I can't access to AssetManager from unit tests to get the *.json files. I tried to mock it:

    for (path in mockPaths) {when<Any>( context.assets.open(path)) .thenReturn(getClass().classLoader.getResourceAsStream(path)) }

    But this doesn't works. Do you know how the library can be configured for testing?

    Thank you!

    opened by alextfos 2
  • Generic mock responses

    Generic mock responses

    As discussed here, I have removed the MockedResponse and adjusted the OkHttpMockInterceptor to allow generic json responses. The status code is not parsed anymore and therefor 200 by default.

    opened by Faltenreich 2
  • JSON Array cannot be used as root element

    JSON Array cannot be used as root element

    First of all, I would like to thank you for this awesome and very convenient library! It makes perfect sense in our emerging application since our API is still under development.

    I have an endpoint that responds with a JSON array: [ { ... }, { ... }, ... ]

    I would like to reuse this exact same JSON from the API, but currently I have to adjust these responses before I copy them into the assets in order to match your specification: { "status": 200, "response": { "items": <actual array from above> } }

    Otherwise I get the following IllegalStateException from GSON, since it expects an object as defined in the MockedResponse.java of your library: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

    I would like to ditch the surrounding JSON object and parse only the array. Is this possible?

    opened by Faltenreich 2
  • List of strings

    List of strings

    What about reading an array of something? I mean, in the example there is a Observable<ArrayList<String>> getUserNumbers , but it didnt work. It give me the following error "Error opening asset api/v1/users/1/phonenumbers.json" (ive openned your project and tested in it) How can this be fixed? In order to make a "workaroud", I need to create a model object that contains this list, but this didnt feel 'right' to me. thanks.

    opened by andersonbadari 1
  • Same path and different HTTP methods

    Same path and different HTTP methods

    If I have requests with the same path and different HTTP methods. How do I organize the json models in the assets folder to correspond?

    For example, how do I get different responses for GET api/v1/posts and POST api/v1/posts?

    Thanks!

    opened by toureholder 1
Owner
Mad Mirrajabi
Awesome developer!
Mad Mirrajabi
A basic list application designed using MVVM pattern with Retrofit, OkHttp, and Hilt for dependency injection

FRExercise A basic list application designed using MVVM pattern with Retrofit, O

null 0 Dec 22, 2021
NiceHttp - A small and simple OkHttp wrapper to ease scraping

NiceHttp - A small and simple OkHttp wrapper to ease scraping

LagradOst 19 Dec 17, 2022
SimpleInterceptor for okhttp

SimpleInterceptor Simpleinceptor is the interception interface tool of Android okhttp client, which is convenient for testing or development and quick

zhonghua 25 Jun 21, 2022
Customizable OkHttp Logging Interceptor

An OkHttp interceptor which logs HTTP request and response data and allows output customization.

Bartek Wesołowski 22 Aug 13, 2022
A "fluent" OkHTTP library for Kotlin based on string extensions.

okfluent A "fluent" OkHTTP library for Kotlin based on string extensions. Do not take this project seriously, I just wanted to show that this kind of

Duale Siad 0 Nov 23, 2021
A Beautiful Log Printer For OkHttp.

LogDog A Beautiful Log Printer For OkHttp. It looks like this: Import repositories { maven { url 'https://jitpack.io' } } //something else... impl

Michael Lee 3 Jun 21, 2022
Kotlin-REST-Retrofit - Simple client to consume a REST API with Retrofit using Kotlin

Kotlin REST Retrofit Sencillo cliente para consumir una API REST con Retrofit us

José Luis González Sánchez 5 Nov 4, 2022
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
Display list of item from local Json and download, view after downloading

Download App Features: ● Display fake responses for the list of videos and books ● choose one or multiple files to download, ● show the download perce

Mahmoud Othman 1 Dec 25, 2021
Ktorfit - a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit

Ktorfit is a HTTP client/Kotlin Symbol Processor for Kotlin Multiplatform (Js, Jvm, Android, iOS, Linux) using KSP and Ktor clients inspired by Retrofit

Jens Klingenberg 637 Dec 25, 2022
Retrofit + OkHttp3 + coroutines + LiveData打造一款网络请求框架

Network-Demo Retrofit + OkHttp3 + coroutines + LiveData打造一款网络请求框架 一个好的网络框架需要有那些特点呢? 请求 当然这个请求不单单是发送请求这么简单,它包括请求相关的一系列配置是否简易、发送模式是否灵活切换、请求头信息是否易处理、请求参数

图你怀中安稳 77 Nov 14, 2022
Latihan Networking dengan Retrofit

Latihan-Background-Process-dan-Networking-9 Latihan Networking dengan Retrofit Pada materi kali ini Anda akan belajar menggunakan Retrofit untuk menam

Ubean 0 Nov 25, 2021
Exercicio praticando Retrofit

MarsPhotos - Starter Code Starter code for Android Basics in Kotlin. Introduction Using this stater code you will create MarsPhotos is a demo app that

Lucas Caetano 1 Nov 26, 2021
기존 post-sample Repository 공부한 기술들로 다시 만들어보기 (MVVM, Hilt, Coroutine/Flow, DataBinding, Retrofit, Moshi, Jetpack)

post-sample-hilt-jetpack 기존 post-sample Repository에서 새로 학습한 부분 도입 기존 코드 변경 (Observe) LiveData -> Flow / StateFlow (DI) Dagger2 -> Hilt (Asynchronous)

훈성 9 Nov 15, 2022
Retrofit Flow Call Adapter Factory For Android

Summary Android Retrofit FlowCallAdapterFactory Retrofit 2 CallAdapter.Factory f

TaeHwan 12 Aug 3, 2022
HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps

HttpMocker HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries. It ca

David Blanc 174 Nov 28, 2022
Write your asynchronous Network / IO call painlessly in Kotlin !!

Asynkio : Write asynced IO/ Network calls painlessly on android | | | Documentation Write your network requests, IO calls in android with Kotlin seaml

Nikhil Chaudhari 82 Jan 26, 2022
A library that observes your network status.

A library that observes your network status. Update in progress ... Download Using gradle In your root build.gradle at the end of repositories add all

Moses Wangira 9 Apr 18, 2022
Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

VK.com 104 Dec 12, 2022