• Stars
    star
    245
  • Rank 165,304 (Top 4 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

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

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.

More Repositories

1

search-dialog

An easy to use, yet very customizable search dialog
Java
514
star
2

view-effects

Apply custom effects on view backgrounds
Java
178
star
3

duration-humanizer

361000 becomes "6 minutes, 1 second"
Kotlin
61
star
4

kotlet

Just another Kotlin sample Android application which uses MVP architecture, Dagger2, Retrofit + Okhttp, RxJava etc.. plus some docs I've collected
Kotlin
27
star
5

annotation-processor-sample

An annotation processor which implements "Builder pattern" for your java classes.
Java
24
star
6

firebase-chat-sample

A sample app that shows basic usage of Firebase Auth and Database in form of a very simple chat hub app
Java
21
star
7

aider-github-action

Run Aider AI assistant in your Github Workflows!
Shell
14
star
8

aider-github-workflows

Workflows that use aider-github-action
10
star
9

sdxl-turbo-mac-mps

Run Stable Diffusion XL Turbo on Mac M1/M2
Python
9
star
10

kotlin-preferences-extensions

A set of RxJava2 Extensions to get/set values of SharedPreferences in a super simple way
Kotlin
9
star
11

een-een-twee

πŸš‘ πŸš“ πŸš’ To become more paranoid, or not to become more paranoid, that is the question.
TypeScript
3
star
12

cf-render

✨ Convert your CloudFormation and CDK code to visuals! ✨
TypeScript
3
star
13

electric-field-demonstration

Electric field demonstration in Unity3D
C#
2
star
14

simple-bank-system

This was a simple stupid university project. The goal was to make a simple bank deposit/withdraw system in C#
C#
1
star
15

aider-github-workflows-test

A repo to test aider-github-workflows on
TypeScript
1
star