Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate no network using Retrofit and MockWebServer

I want to simulate the no network case when using RetroFit and MockWebServer.

Im currently testing using Espresso and supplying the MockWebServers url to the RestAdapter before I start my tests. This works great for mocking server responses and so on but I cant see a simple way to script the java.net.ConnectException exception thrown when a device has no network. I can see the MockResponse allows throttling simulation and so on but not a custom exception.

I know I could go the root of mocking the actual web api interface used by retrofit but I would like to use the same approach as my other tests if possible by using MockWebServer.

I imagine I've just missed something simple :)

Thanks

like image 639
Dori Avatar asked Jul 25 '14 09:07

Dori


3 Answers

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.

like image 144
Jake Wharton Avatar answered Nov 05 '22 19:11

Jake Wharton


The easiest way to simulate network issues with MockWebServer is by setting the SocketPolicy to SocketPolicy.DISCONNECT_AT_START, SocketPolicy.NO_RESPONSE or etc:

MockWebServer server = new MockWebServer();

MockResponse response = new MockResponse()
  .setSocketPolicy(SocketPolicy.DISCONNECT_AT_START);

server.enqueue(response);

This way you can simulate network errors like connection prematurely closed before response or Timeout exceptions

like image 12
Konstantin Grech Avatar answered Nov 05 '22 18:11

Konstantin Grech


to be clear with whe types of exceptions here you can see the differences:

Internet Connection Error

So you can get two types:

UnknownHostException - When you don't have internet or unknown host... to simulate this, set to the adapter an incorrect end point.

ConnectException - mockwebserver can throw a timeout exception. You can see how to do it here:

https://github.com/square/okhttp/tree/master/mockwebserver

Really I don't know how your code is, but I hope this is useful

like image 7
mromer Avatar answered Nov 05 '22 17:11

mromer