Simulate no network using Retrofit and MockWebServer

Retrofit has a retrofit-mock module which offers a MockRestAdapter class whose purpose is to simulate network delay and errors.

This is a used in conjunction with the normal RestAdapter to create an instance of your service. You can see a full example in the samples/mock-github-client/ folder of the repo: https://github.com/square/retrofit/tree/parent-1.9.0/retrofit-samples/mock-github-client

MockRestAdapter offers these APIs:

  • setDelay – Set the network round trip delay, in milliseconds.
  • setVariancePercentage – Set the plus-or-minus variance percentage of the network round trip delay.
  • setErrorPercentage – Set the percentage of calls to calculateIsFailure() that return true.

In your test, you can call setErrorPercentage(100) to guarantee that a network error will occur. By default the amount of time for the error to be thrown is anywhere from 0 to 3x the delay. Set the delay to 0 for instant results.

Leave a Comment