Okhttp Json Mock


Source link: https://github.com/mirrajabi/okhttp-json-mock

okhttp-json-mock

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.

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:1.1.1'  
}

1. Add OkhttpMockInterceptor to your OkhttpClient instance and attach it to yout 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();

Constructors

OkHttpMockInterceptor(Context context, int failurePercentage) OkHttpMockInterceptor(Context context,

  int failurePercentage,

  int minDelayMilliseconds,

  int maxDelayMilliseconds) OkHttpMockInterceptor(Context context,

  int failurePercentage,

  String basePath,

  int minDelayMilliseconds,

  int maxDelayMilliseconds)

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 

Notes

JSON Response models

The base response model is MockedResponse.java so the json response should look like the ones below :

1. Response is a single object(not an array)
{

"status": 200,
"response": {

  "id": 0,
  "name": "John",
  "lastName": "Doe",
  "age": 20,
  "phoneNumbers": [

 "0123456789",

 "3215467891",

 "1645189442"
  ]

}
 
}

where response object is the result that the interceptor will return

2. Response is a list of objects(e.g. an arraylist)

in this case the items object in response is the array that will be returned.

{

"status": 200,
"response": {

  "items": [

 {

"id": 0,

"name": "John",

"lastName": "Doe",

"age": 20,

"phoneNumbers": [

  "0123456789",

  "3215467891",

  "1645189442"

]

 
}
,

 {

"id": 1,

"name": "Jane",

"lastName": "Doe",

"age": 22,

"phoneNumbers": [

  "1532131512"

]

 
}

  ]

}
 
}

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

1.1.1 - Fixes file name lowercase issue

1.1 - Adds delay customization option.

Resources

Android button which can morph from one shape to another.

Android Test Automation.

Android library for Wearable Internet of Things class at URI. It provides wrappers to Google Play Services, and base classes for simple development.

AndroidChannel is helper library for inter thread communication between main thread and worker thread. AndroidChannel uses HandlerThread for inter thread communication.

A custom view for Android with an animation for status changing.

A pretty menu with rotation effect.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes