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
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.
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
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
I don't know if it's useful, but you can simulate a timeout with MockWebServer:
String contentType = "Content-type: application/json";
MockResponse response = MockResponse().setResponseCode(statusCode).setBody(responseBody).addHeader(contentType);
MockWebServer proxy = new MockWebServer();
proxy.enqueue(response);
proxy.setBodyDelayTimeMs(timeoutDelay));
proxy.play(10000); //Number port - Important!!!
Note: Please, set HttpClient of your code (e.g. AsyncHttpClient) with that number port for testing purpose.
What worked for me is pointing the Retrofit URL (end-point) to a random non-existent host .
I used "thisIsARandomHost.com" and bingo i was able to mock the unknown host exception.
For example : setAPP_URL = "http://thisIsARandomHost.com/";
Here , setAPP_URL is the string variable that contains my url which I pass on to retrofit , when I want to mock unknown host exception in my tests I set the url as above .For all other purposes it is set to the valid URL required by my app.
As stated in above answers , MockWebServer is a great library for mocking retrofit responses , but you don't need that library for mocking this exception . For mocking all other exceptions I would recommend MockWebServer , I use it a lot in my project for testing responses.
Note : You can set the app url to anything as long as that url doesn't exist on the web.
mockWebServer.shutdown() before executing your unit test is fine.
Internally it closes the socket connection:
serverSocket!!.close()
Related
I Want to know what is the recommended value for methods setConnectionTimeou() and
setReadTimeOut() for HttpURL connection? I know these value depends upon the server and what task server is performing. but still i want to know the recommended values for these method.
It's hard to answer such question without knowing the typical response time. Users are fairly accustomed to wait a few seconds when using mobile devices whilst on mobile networks.
Personally if the timeout is between 10 - 15s I will consider it a normal latency, if it is 20s or more, I will most likely quit the app.
From Default Documentation
Both setConnectTimeout (int timeout) and setReadTimeout (int timeout) From API 1
A SocketTimeoutException is thrown if the connection could not be established in this time. Default is 0 which stands for an infinite timeout.
see this link its give you more idea about this.
https://www.nngroup.com/articles/website-response-times/
You can do it this example:
Your method
How to add parameters to HttpURLConnection using POST
OR
You can follow this other form
https://developer.android.com/reference/java/net/HttpURLConnection.html
I running into an issue routing network calls using OkHttp. I'm trying to send HTTP requests to a local device (via the device's ip) using an Access Point that has no internet access. Due to some changes in Android 5.0, OkHttp will try to route the request over data instead, which then fails.
In Android 5.0's Network API, I could use the NetworkCapabilities class along with the NetworkRequest.Builder in order to tell the request to only go over Wi-Fi, However, I'm already using OkHttp and I don't want to overhaul my code. Is there anyway to do a similar thing with OkHttp?
I came up with a workaround:
final Network currentNetwork = (Network) network;
newClientBuilder.socketFactory(((Network)network).getSocketFactory())
.dns(new Dns() {
#Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
return Arrays.asList(currentNetwork.getAllByName(hostname));
}
});
We’d like to eventually include such functionality directly in OkHttp, and you might be the first volunteer/victim to test things out. What you probably want to do is use OkHttp 2.6’s new Dns interface to call through to the network of your choice. If that works, either the IP address will cause OkHttp to do the right thing anyway, or you’ll also need to replace the SocketFactory.
i am trying to develop a cordova(3.5.0) project in android platform and in that i have to check network connection availability before each API call. for that i am using 'navigator.connection.type',and some times it return 0. why this is happening? plz help me for solving this trouble
Without some more details I can only guess.. There are some conditions which may cause this.
navigator.connection.type = 0 -> connection type unknown.
So you may have a connection, you may not it simply hasn't been determined yet, or because of privileges the device isn't saying.
Are you calling this check too early? ie before deviceready
In our app we do not check the connection each time but we handle it this way:
by making the API request anyway, knowing that its possible to fail, we set a timeout and error handling. If it fails by error or timeout we check connection type and then ping the server with a simple "hello" "acknowledge" request. Its a super small request that we figure will work or if it timeouts again the connection must be so poor it might as well be disconnected.
This is because there are really two types of connection you need to check. Many miss this!
And also because its navigator totally lies some times... :/
Just because wifi is on and connected and navigator tells you this, it doesn't mean you will have a connection to the outside world. You need to check the network hardware (which is all navigator will tell you) but you must also check network connectivity, if this is something you are sensitive about.
I am using the class HttpUrlConnection for requesting JSON responses
I realized that no matter if I set or not
System.setProperty("http.keepAlive", "false");
The first response is always going to take longer, while the next responses are very quick, with and without keepAlive. I am not even using SSL.
Notice that, my app doesn't need to perform any authentication with the server, so there isn't any startup call to the webservices. The first request I make to the webservices is actually the very first.
I am also verifying server-side with "netstat", that by setting keepAlive false on the Android client the connections disappear straight away, while without specifying keepAlive false they keep staying as "ESTABLISHED".
How can you explain that subsequent responses are quicker even if the connection doesn't persist?
ANDROID CODE:
line 1) URL url = new URL(stringUrl);
line 2) HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
line 3) InputStream instream = new BufferedInputStream(urlConnection.getInputStream());
Until line 2 everything always gets executed very quickly, either with keepAlive or not. Line 3 in the first request takes around 3 seconds, while in all subsequent always less than 1 second. Each request is about 0.5KB gzipped.
SYSTEM:
I am testing using a Nexus 5, connected via 3G
My webservices are written in Go, running on a CentOS 6.4 linux server
I am using standard tcp v4
UPDATE:
For the moment I have decided to use a trick: when the fragment is resuming, I make a HTTP HEAD request to the server. In this way all subsequent calls in the next 10 seconds are very quick. If the user waits more than 10 seconds then the first one will be slow, and the next ones will be quick again. This is all happening without using KeepAlive.
It's a really big mistery now. It looks like there is some kind of "awake" period which lasts for about 10 seconds. I don't think there is anything strange on my code which can result on that. Also because everything seems to happen during the line 3 I reported above.
SOLVED! thanks to Mark Allison!
Here is a very clear explanation:
http://developer.android.com/training/efficient-downloads/efficient-network-access.html
Also, everything can easily be monitored using Android DDMS's Network Statistics. If you wait some seconds (let's say 20) from last request, you can see that it takes 2 seconds to transmit a new request.
I suspect that the lag that you are seeing is simply down to the cellular radio transitioning from either low power or idle state to full power (which can take over 2 seconds).
Check out Reto Meier's excellent DevBytes series on Efficient Data Transfer for an in-depth explanation of what's going on.
The first request cannot leverage a keep-alive obviously, because thankfully Android doesn't keep the connections alive for minutes or hours. Only subsequent requests can reuse keep-alive connections and only after a short period of time.
It's natural that you have to wait in line 3. Before something like conn.getResponseCode() or conn.getInputStream() the HttpURLConnection is in CREATED state. There is no network activity until it's getting in CONNECTED state. Buffered* shouldn't make any difference here.
I've observed long delays when using SSL and there was a time-shift between server and device. This happens very often when using an emulator which is not cold-booted. For that I've a small script running before test. It's important that PC and emulator are in the same time-zone, otherwise it's very contra-productive: (see below, because it's hard to show the command inline).
I can imagine that Android saves battery in putting 3G into sleep mode when there is no activity. This is just speculation, but you could make a test by creating some other network activity with other apps (browser, twitter, ...) and then see whether your app needs the same long "think time" until first connection.
There are other good options for losing time: DNS resolution, Server-side "sleep" (e.g. a virtual machine loading "memory" from disk).
The command to set time of Android emulator:
adb -e shell date -s `date +"%Y%m%d.%H%M%S"`
Edit
To further analyze the problem, you could run tcpdump on your server. Here is tutorial in case you don't know it well. Store the dumps to files (pcap) and then you can view them with wireshark. Depending on the traffic on your CentOS server you have to set some filters so you only record the traffic from your Android device. I hope that this gives some insight to the problem.
To exclude your server from being the bad guy, you could create a small script with curl commands doing the equivalent as your app.
You could create a super-tiny service without database or other i/o dependencies and measure the performance. I don't know "Go", but the best thing would be a static JSON file delivered by Apache or nginx. If you only have Go, then take something like /ping -> { echo "pong" }. Please tell us your measurements and observations.
Instead of using so many classes I suggest you use this library
you can have a look at here
http://loopj.com/android-async-http/
your code will become very very less , instead of declaring so many classes writing bulk of code , you can just use 4 lines of code
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
It is very efficient in geting the response very quickly(1 or 2 secs including parsing).
I hope this will help you out. :)
I perform some large downloads. I start a download being connected to 3G, all is fine. Then, I switch to WiFi connection, but the request returns a timeout exception. I have used HttpClient library. I have implemented a retry mechanism, so, when the request returns an exception, it sleeps for 0.5 seconds and tries to execute again and again. I would expect that, after connecting to a WiFi, the Http request could execute. But it seems that the Http execute method returns a null response, all the time after that. Very strange, if I commute again to 3G, the execute method returns again a good response. Can anyone help me please :) ?
First, it seems that it may be more convenient to use DownloadManager for large files - it handles retry and everything.
As for HttpClient - it's known to have some issues, but i'm not sure if you bumped into one of them or just overlooked something. It's been deprecated as of Gingerbread, you may want to try HttpUrlConnection instead, it's said to have less problems than HttpClient.
Also, when switching between WIFI and cell connections, HttpClient may need to be reinitialized completely, there's http range header to tell server which byte you want to continue downloading from. But again, I suggest you give DownloadManager a try, it may save you a lot of time.
This might be a routing problem:
when switching between different network types usually the local ip address and, more important, the local routing table changes, due to a different gateway being used. This means that packages that traveled fine between client and server wont reach any destination after a network change, if they are send the same route. Most likely your client implementation has to be notified of the change or even restartet completely, so that the routing strategy is reinitilized.
If the documentation of the implementation components you use dont reveal anything you could try to track this down using a package sniffer like wireshark. Typically packages running into nirwhana show up easily there.