Android MVP testing methods that needs network operations - android

I'm testing my app using Junit and Mackito, testing methods is gone good so far but not with methods that need network operations, how to test them properly, so that the assert is called after fetching data from the backend?

In general you should test your app, not server side logic. So just mock methods which do network calls.
But, if you want to test network layer of app itself, there is good way, which I recommend, to do that - WireMock
Simply saying it creates locally running webserver which response with predefined responses.

Is not a good idea test methods that depend on network calls.
Better test backend apart and mock it in client.
Anyways, if you want to wait for the data use: Thread.sleep(Xms) in test method after network call and before your asserts.
#Test
public void testcase() throws InterruptedException {
// make actions and network call
// Wait, for example 2 seconds. It depends a lot of connection
Thread.sleep(2000);
// Then assert whatever you want
}

Related

Best way to intercept a network call and providing mock response while UI testing

I am testing a login page on an android project and would like to intercept when the call is being called (When a button is clicked) and provide with a mock response (200 or 401 for ex) to prevent actually calling the network every time and to make automated unit testing faster. I usually just provide correct username/pass and Thread.sleep for a few until the request is done and I know this is not the correct way.
I am using retrofit 2 for my network calls and Espresso for UI testing.
I know how to mock a retrofit call but I want to mock exactly when the call is being executed in the login activity and send that activity a mock response.

Mocking API responses for Android Test

I want to mock the API responses for my Android Async Network Tasks for Unit Testing. Anyone can tell me how to do this? I'm beginner to testing in Android.
Create your own class implementing the same API as your 'real' networking class. When one of its methods, say, method requestData() gets called, wait a bit inside the method then return some mock data in the same way as the real class is supposed to do.

Functional tests in android. How to wait for fragment result?

I'm trying to add test to a quite big android project. So, I'm able to add the test, both to activity both to fragments, and get they run correctly.
But in my case, most of the fragments, when started, starts a Runnable into a new Thread. This thread connect to APIs, request and parse data, and return them to a handler, in the calling fragment.
The question is: How am I supposed to ask the test to wait until the data are retrieved by handler, so I can check them values?
How about instead of waiting for the values to return from real objects. You create mock objects that can return whatever value want instantly. Mockito is a great mocking framework that is very easy to use on Android.
http://code.google.com/p/mockito/
The way you go about using it is to create mock objects as opposed to real objects and you have to find "seams" to insert them into your tests. With a mock object, you can get it to return whatever value you want for any of its methods. With a mock object you can isolate dependencies. Therefore, in your example, you may want to create mock objects that mock the object that is connecting to the api because then you can return whatever value your tests need for the server to return to test whichever part of your app that you are testing. For example, if your testing whether the signUp activity is opened if the server returns that the user has entered a wrong password, you create a mock object that will return false to your activity and then insert that into where the real object is supposed to be.
Most people have issues testing existing code (that was not built with testability in mind) because there usually aren't any seams to insert test objects. Check out this awesome blog about how to make code more testable. It is contains really great advice.
http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html

Using excessive amount of network calls in android

I am developing an android application that needs to communicate a lot with a remote server. For this task I wrote a class that handles all the network communication.
Do I need to make for every single method as an Asynctask? What about methods that I am dependent on for the rest of the code execution? (thus needs to be done synchronously - like waiting for an answer on registration?)
I am asking this because I already had a small app before to communicate with a remote server and I didn't use any Asynctasks, this one crashes on every method being called though.
Edit -
Meanwhile - before making a class of my own I found a great tutorial related to a google libraray that already handle that the libraray name is Volley the tutorial I looked on is this one
Yes, every network call has to asynchronous. You don't need to make every single method in you class async, but i would refactor the code in a way that only one peace of code actually does the calls and this peace has to be async. If you have following code that depends on the response from the server, then use a callback.
In pseudo code that would look something like this:
void makeNetworkCall(command, listener){
async(){
result = command.execute();
listener.onCommandSuccess(result);
}
}
Do I need to make for every single method as an Asynctask?
Yes. Android requires networking code to be executed asynchronously, so the user interface never gets blocked.
What about methods that I am dependent on for the rest of the code execution?
You can wait for an Asynchtask to finish execution. Refer to this question.

Android best practice AsyncTask

I am new to Android Development. Sorry for a dumb question.
I need to check several http resources (resource1, resource2... etc) and check if they are up. If resource 1 is unavailable, then the app needs to check if internet is up (probably ping google?) and then if the connection is actually working it needs to check all the other resources and place the information about what is down to the notification drawer.
It's pretty straightforward to do it with AsyncTask and HttpURLConnection for one resource but i don't quite understand how to follow execution logic with async calls (resource1 -> google -> resource2 -> gather info in one place -> display notification). What is the best practice for it?
#FD_'s answer is valid but I think there is a better way that avoids the horrors of the Async Task. For the record I upvoted FD_'s answer as it is valid I am just pointing out another way.
So I would make a result object. This can be used to work out what happened when you tried to communicate with the various services. You could have something like
public class ResponseResult {
public String displayName; // so we know what this was all about e.g. "google request"
public boolean success;
public String message;
public int httpStatusCode; //useful to help workout what went wrong e.g. 500, 302 etc.
}
You could then use something like the Android Volley Library that is better than an AsyncTask as it uses a RequestQueue in another thread, which survives the Activity lifecycle better. It also might make your code a little easier to read/manage.
You can read a little about Volley Vs AsyncTask here - Volley and AsyncTask
Once you have issues all your requests and put the results in an Array or List, you could then iterate over them to print the result.
You can get Volley from here https://android.googlesource.com/platform/frameworks/volley
Additional Info
You might also find this inforgraphic from Robospice to be useful as it helps to explain the drawbacks of an AsyncTask.
https://raw.github.com/octo-online/robospice/master/gfx/RoboSpice-InfoGraphics.png
Another implementation
You may find this implementation is not suitable but it makes some sense and would produce even less code.
You could write some server side code to do the checks for you and return an XML/JSON array of result objects. This has the advantage of a single request to a hardwired server with a more reliable connection, that possibly could make the requests in a shorter space of time.
Your Android device would only issue a single request to the server and then process the result array per my other method above.
The major drawback is that this would introduce another set of code and additional hardware.
I would encourage using Volley library for that purpose also. Check past Google IO 2013 interesting video about it.
Advantages of using Volley:
Volley automatically schedule all network requests. It means that
Volley will be taking care of all the network requests your app
executes for fetching response or image from web.
Volley provides transparent disk and memory caching.
Volley provides powerful cancellation request API. It means that you
can cancel a single request or you can set blocks or scopes of
requests to cancel.
Volley provides powerful customization abilities.
Volley provides Debugging and tracing tools
VIDEO: Google I/O 2013 – Volley: Easy, Fast Networking for Android
**source*: http://www.technotalkative.com/android-volley-library-example/
On the other hand, once one of those resources is unavailable, you don't have to ping google as you said. Android API has facilities to check whether your mobile is connected to the Internet; something like this would be enough:
private boolean isConnectedToInternet() {
return (((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null);
}
Just perform all your logic and internet operations in one place, in the same AsyncTask. Create a class that holds all result information and implement your AsyncTask to return (eg send to a delegate/listener/call main thread method) an instance of that class.
If you like to execute your async task using similar syntax as Jquery's $ajax, this article shows you how to do it. With very little code in the article and Java 8's lambda expression, you will be able to write your async code like this:
Async.run(() -> {
//code will be executed on a background thread
MyAPI api = new MyAPI()
return api.loadData();
})
.whenComplete((data) -> {
//back on UI thread, update UI using data returned
})
.onError((ex) -> {
//handle exception on UI thread
})
.execute();

Categories

Resources