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

A cool android loading effect.

View that supports a foreground, like FrameLayout.

RevealFAB is a simple custom view that provides you intents between activities with ripple animation.

A light-weight image cropping layout, allowing UI customization and cropping box update listener. Image and the selected area (cropping box) is scale and fit into the predefined area.

A Gradle plugin for Android which generates both Java and XML constants as part of the build process.

The one true exception handler for Android.

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