OkResponseFaker


Source link: https://github.com/Sloy/okresponsefaker

OkResponseFaker

OkHttp response faker. Provide "fire and forget" or persistent fake responses to OkHttp3 through interceptors.

Description

OkResponseFaker uses a special OkHttp Interceptor that allows you to provide a custom response for the next or more requests executed, allowing you to easily debug feedback to special cases in your application. You can fake response status and body using the FakeResponse interface. Use simple static data, or build a complex response using JSON objects. Your choice.

Gradle

Just import the library from jcenter:

dependencies {

  compile 'com.sloydev:okresponsefaker:2.0.0'
  compile 'com.squareup.okhttp3:okhttp:3.4.1' // requires OkHttp 3 
}

You can add the optional JSON module if you want to build JsonFakeResponse using JsonAdapters:

dependencies {

  compile 'com.sloydev:okresponsefaker:2.0.0'
  compile 'com.sloydev:okresponsefaker-json:2.0.0'
  compile 'com.squareup.okhttp3:okhttp:3.4.1' // requires OkHttp 3
  compile 'com.sloydev:jsonadapters-core:0.1.0' // included in okresponsefaker-json, but whatever
  // ... 
}

Setup

You just need to add a FakeResponseInterceptor to the end of interceptors chain when creating your OkHttp client. There are two easy of using OkResponseFaker: singleton or custom instance. Check the diferences in the usage section.

public OkHttpClient createClient(){

OkHttpClient client = new OkHttpClient();

client.interceptors().add(...);

client.interceptors().add(ResponseFaker.interceptor());
 // singleton way
// or
client.interceptors().add(fakeResponseInterceptor);
 // instance way
return client; 
}

Usage

The simplest way of using the library is through ResponseFaker class and its static methods. It contains a singleton instance of FakeResponseInteractor and wraps its method calls so you always use the same interactor everywhere.

But you can also create your own instance of FakeResponseInteractor and call its methods directly. This is useful if you have a dependency injection setup and you want to manage your objects lifecycle yourself. All the examples below apply to both ways, since they use the same methods.

Fake a response

Provide any instance of FakeResponse. You can use your own or a built-in one.

public void fakeMyResponse(){

ResponseFaker.setNextFakeResponse(new FakeResponse(){

  @Override
  public String body() {

return "this is a fake response body";
  
}

  @Override
  public int httpCode() {

return 404;
  
}

  @Override
  public String mediaType() {

return "text/plain";
  
}

);
 
}

Right now the only built-in response type is EmptyBodyFakeResponse

public void fakeNotFoundResponse(){

ResponseFaker.setNextFakeResponse(new EmptyBodyFakeResponse(404));
 
}

Trigger more than once

By defaut fake responses are triggered in a "fire and forget" manner, meaning that they will be used once only. To avoid this and keep using the fake response until you manually cancel them use the method setTriggerOnce(boolean)

ResponseFaker.setTriggerOnce(false);

This flag doesn't change with a new fake responses, you must set it to true to revert back to "fire and forget" mode, or stop using the fake response with clearNextFakeResponse():

ResponseFaker.clearNextFakeResponse();

Json Responses

If you use the optional Json module you can very easily fake the contents of a response using objects:

public void fakeEmailInUseResponse(){

ResponseFaker.setNextFakeResponse(new JsonFakeResponse(myJsonAdapter,

  new EmailInUseError(),

  HTTPCODE_INVALID_REQUEST);
 
}

This is super useful if you already have classes representing your server's errors.

Best served with

By its own this library isn't that great. But you can really take advantage of its power when using it with some debugging tools like Stetho's dumpapp or a Debug Drawer with debug actions as seen in Jake Wharton's u2020.

Demo

There isnt't a demo project for this. I think the snippets above make it clear enough. If you think it isn't and have a simple project demo idea, open an issue or pull request.

Contributing

This little library was made for internal usage, and then published to public usage. It's very small and simple, I've just added what we needed. If you consider that it could have more or nicer features, go ahead an pull request! I will gladly accept contributions and new features.

Resources

Fast JSON parser for Java projects. The following scalar types are supported:

  • String
  • boolean/Boolean
  • int/Integer
  • long/Long
  • float/Float
  • double/Double

If a json field is another dictionary, it can be represented by another model class. That model class must also have the @JsonType annotation.

Lists of objects are supported either as Java Lists or Queues.

Mimicry is a tiny Android library (actually just one class) to format items in a ListAdapter to display as a grid.

Why not just use a GridView? Because a MimicryAdapter can be used with other ListAdapters!

Encryption is a simple way to create encrypted strings to Android project.

SnappyDB is a key-value database for Android it's an alternative for SQLite if you want to use a NoSQL approach.

It allows you to store and get primitive types, but also a Serializable object or array in a type-safe way.

SnappyDB can outperform SQLite in read/write operations.

AppRate for Android is a library that allows your users to rate your application in a non intrusive way. A window with options to rate, remind later or reject is displayed according to your configuration

Android @Properties provides a simple way to read a .properties from assets folder.

You just have to extends from AssetsProperties and use @Property annotation to invoke the automatic property mapping.

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