I am using Mokitio in android to run unit test cases.
.
What i am trying to do: There is a block of code in onCreate event
of the activity
I am trying not to run this block of code during Running Unit test
cases and run it during app regularly.
Is it possible to do something like that using mokito because mokito synchronizes for activity life cycle
The proper solution here is to change your design a bit. You should not think in terms of code blocks, but in terms of functionality.
The way of preventing that some x lines of code are run in a certain environment, but are not in some other context ... is by using proper OO means.
Meaning: first create an interface that describes the functionality of those lines of code we are talking about:
public interface DoTheFoo {
public void foo(Bar bar);
}
Then you create a "production" implementation DoTheFooImpl of that interface (which as a side effect: you might be able to write proper unit tests for as well).
Finally: within your class that needs that functionality, use dependency injection to acquire an object providing the DoTheFoo interface. In your production environment, that would be a DoTheFooImpl object; but for your unit testing, you would simply create an mock for it - configured to do nothing upen calls to foo().
Of course that sounds like a bit of work; but the point is: currently, your design is somehow deficient. And instead of trying to go for dirty hacks/workarounds, consider looking at your design to identify a more elegant way to resolve your problem.
Related
I have a method that formats a number, and I wanted to test it.
I built a test calling this method and the result showed that: decimalFormat.setRoundingMode(\* Any rounding mode \*);
doesn't work. It always takes the default RoundingMode.HALF_EVEN.
My method works fine - decimalFormat.setRoundingMode(RoundingMode.HALF_UP); do work when running the app (I copied the test to the app and logged it..)
Why can't I call decimalFormat.setRoundingMode() in a unit test?
Please post your code. Replace the RoundingMode.HALF_UP value with its hard coded primitive value (the value behind it).The static call to RoundingMode might be the cause of this.
It also seems to me that your unit test is wrong, you're checking a behavior of a class based on an existing implementation of your dependency (decimalFormat). You should never do this in an unit test instead you have to mock decimalFormat away and test the behavior of your method independently from the implementation of 'decimalFormat' or any other dependency.
In instrumentation tests, should I use com.robotium.solo.Solo#clickOnView or android.view.View#performClick?
Both of those functions require View object.
Checking javadoc and source code, functionality is similar.
But implementation is quite diffrent
android.view.View#performClick calls sendAccessibilityEvent then registered event listener.
com.robotium.solo.Solo#clickOnView(android.view.View) simulates actual finger click, on given screen coordinates (sends MotionEvent).
Are there any circumstances when should I use robotium function? It looks like it is just a lot of slower and more fragile way of having exactly same end result like android.view.View#performClick.
Everyone using Robotium for GUI testing.
Can you tell me what Android native test framework cannot do that Robotium can do?
As I know Robotium can be used as black box testing, so I do not need to know about application resources.
What else?
Robotium
pros:
support hybrid applications with webViews.
you can bound your test to unique IDs of tested application whenever with UIatomator to write complicated test cases will need great amount of work from you
in UIatomator is used UiAutomatorTestCase Instrumentation which doesn't give you possibilities to call current activity and check that loaded appropriate one, you can't call connectivity- or audio- managers for wi-fi or sound tests. In Robotium you can easily call such gems and that is greatly improve efficiency of your tests
Open source project, so you can modify tool to your needs
cons:
No possibility to tests multi-process application where android:process tag used for different activities.
example code:
UIautomator
pros:
Test case is independent from the process at which tested application works. So it can be used in places where are used additional libraries or activity is run in other process also useful if for test needed switching between several applications.
cons:
Works only on Android version 4.1 or more!
You can't use source IDs when you get ui-object instances. That mean if an application structure changed on one layout you need to refactor your test (this problem can be solved by using tags for each ui-element)
You can't get current activity or Instrumentation. That mean you are limited in development of your tests and not used many of android's api methods for your tests.
Hard to debug, you need to have script for buiding and starting your test fast and see output
hierarchy viewer:
I think both these tools are good ones, definitely possibility to switch between applications during test is awesome. You should select tool depending from your needs. I suggest Robotium for tests where you don't need to switch between applications because it have simple methods and opportunity to use Android API for writing flexible and smart tests in short code which can cover even testing of a web page inside webview and milti-process applications are very unusual.
The difference between Robotium and the native tools is the fact that with Robotium is really simple to write a test. It's basically point and click, from the Solo instance object.
Here you can download the JAR files and an example project to test it by yourself.
UPDATE
As an example, I'm testing an Activity with some Edit Text, a spinner and a pop-up dialog that shows up when I click a spinner option. Note here that with other methods, filling the fields of the pop up dialog is a real pain.
Here is how to declare the test class and Robotium's initialization
import com.jayway.android.robotium.solo.Solo; //Using Robotium
//Robotium uses ActivityInstrumentationTestCase2.
//Note here the use of the template
public class AddNewQuestionTests extends
ActivityInstrumentationTestCase2<AddNewQuestion> {
public AddNewQuestionTests(Class<AddNewQuestion> name) {
super(name);
}
public AddNewQuestionTests() {
super(AddNewQuestion.class);
}
private Solo solo;
protected void setUp() throws Exception {
super.setUp();
//Initialize Solo with the instrumentation and the activity under test
solo = new Solo(getInstrumentation(), getActivity());
}
And here is the test method:
public void testHappyPathAddScaleQuestion() {
// Type question title
solo.clickOnEditText(0); //find the EditText, and click it
solo.enterText((EditText) getActivity().findViewById(
//find the EditText, and put some string
R.id.activity_add_new_question_editText_question_title),
"Question title scale ");
// Type question description
solo.clickOnEditText(1);
solo.enterText((EditText) getActivity().findViewById(
R.id.activity_add_new_question_editText_question_description),
"Question description scale");
// Type the question
solo.clickOnEditText(2);
solo.enterText((EditText) getActivity().findViewById(
R.id.activity_add_new_question_editText_question),
"Question scale");
// Click the spinner and then the "Scale" question type
//Press an spinner option
solo.pressSpinnerItem(0, 4);
//Wait for the popup dialog title to show up. When robotium reads it, continue working solo.waitForText(getActivity().getResources().getString(R.string.activity_add_new_question_scale_selection_dialog_message));
// Type minimum and maximum ranges
solo.clickOnEditText(0);
solo.searchText(getActivity().getResources().getString(R.string.activity_add_new_question_maximum_value_hint));
solo.clickOnView(solo.getCurrentEditTexts().get(0));
solo.enterText(0, "34");
solo.clickOnView(solo.getCurrentEditTexts().get(0));
solo.enterText(1, "55");
// Click ok to close the dialog
solo.clickOnButton(getActivity().getResources().getString(R.string.OK));
// Click ok to get an ok message
solo.clickOnButton(getActivity().getResources().getString(R.string.OK));
//Wait for the ok toast message
boolean flagOKDatabase=solo.waitForText(getActivity().getResources().getString(R.string.database_success_storing_data),1,120);
assertEquals("Something wrong happened with the database", true, flagOKDatabase);
}
There is no downside to using robotium over the instrumentation framework native to android. That is because when using robotium you can still do everything you could of done without it but you also have access to lots of helpful functions already.
There are other android automation frameworks out there though that are definitely worth looking at. If you have any code in a web view these are especially helpful as this is where robotium really lets itself down.
https://github.com/calabash/calabash-android
https://github.com/calabash-driver/calabash-driver
http://testdroid.com/
I am trying to create unit tests for a REST client that does some API calls. The client works fine in the live application, but I can't get it to run in the test case.
Apparantly, LoaderTestCase.getLoaderResultSynchronously() could be used here (at least according to Android reference, but it will not accept my loader. The code:
public void testGetEventInfo() {
// Init some vars
...
// Create & execute loader
RESTLoader loader = new RESTLoader(getContext(),
RESTLoader.HTTPVerb.GET, action, params, LOADER_GET_NEWS);
getLoaderResultSynchronously(loader);
}
This yields the error getLoaderResultSynchronously(Loader) in the type LoaderTestCase is not applicable for the arguments (RESTLoader).
RESTLoader extends AsyncLoader. Note that I'm using the supportlibrary, maybe the Loader in there is incompatible? The documentation gives no information on this.
I've tried to solve this in several ways, though none seem to work:
Registered a listener to loader. However, the callback never triggers
Using CountdownLatch (also with a listener). Again, no trigger/countdown timeout.
Playing around with the type template (), without success.
Similar solutions on SO, though again failing to reach the listener.
Does anybody know why getLoaderResultSynchronously will not accept the loader? Or another clean way of testing the Loader, including a way to test return data? I can test handling the return data in a separate case, but I would also like to test the actual data.
Sincerely,
Have you taken a look at the source code? You'll find the following import statements:
import android.content.Loader;
import android.content.Loader.OnLoadCompleteListener;
It doesn't look like Android offers a support version for LoaderTestCase. The easiest solution would be to temporarily change to the non-support LoaderManager (that is, have your class make use of the android.content.Loader instead), test your app, and then switch back to the support implementation. You might also consider copying the testing source code into your project, import the support LoaderManager, and execute it directly. I'm not familiar with the test libraries for Loaders but it doesn't seem outwardly obvious that this would cause any major issues.
You can get sources from LoaderTestCase here, create SupportLoaderTestCase class from that sources in your test project and modify all namespaces to support library namespaces (e.g. change android.content.Loader with android.support.v4.content.Loader). Than you can extend your test case from SupportLoaderTestCase (not from LoaderTestCase) and use it without problems
The method you are trying to call (getLoaderResultSynchronously) accepts an object of type android.content.Loader. If your RESTLoader class is not of that EXACT type then you will get this error. I suspect your class directly or indirectly extends android.support.v4.content.Loader, which would explain the error.
I am not aware of a back-port of LoaderTestCase that would support testing of this type of class.
OOTB, Robolectric does not support Locales that well. Therefore, if your app is dependent on locales (which a lot of apps are if they are i18n'nd properly) this can be a royal pain. Long story short, I created my own ShadowFooGeocoder and ShadowFooAddress that allow me to simulate the locale I want. They're basically re-implementations of the existing shadows.
However, when I bind my class as such: bindShadowClass(ShadowFooGeocoder.class), this works great. At runtime, the correct shadow is returned. The problem is that I want to set up the simulations on this object and I'm not sure how. shadowOf(instance) where instance is an injected GeoCoder returns ShadowGeoCoder. I've tried working directly with the ShadowWrangler, but that also returns a ShadowGeocoder.
How can I get at my shadowed class that I've bound through the bindShadowClass(...) call so I can set my expectations (simulations)?
Note: This is a repost of the same question on the Robolectric group here. I posted here because my success rate of getting anyone to answer questions on the group is fairly low. I'm hoping for a better result here.
What I've basically done here is extend ShadowGeocoder like this:
#SuppressWarnings({"UnusedDeclaration"})
#Implements(Geocoder.class)
public class ShadowFooBarGeocoder extends ShadowGeocoder {
// implementation stuff
}
Then I would bind it using the bindShadowClasss(...) and when I retreive the shadow via the static shadowOf(...) call I get back a "ShadowGeocoder" which is an instance of ShadowFooBarGeocoder. I then cast it to that type and perform whatever work I need to.