问题
I have an application with several activities with list views, the selection from the first list view determines the content of the second list view, and the second list view determines the contents of the third, etc.
I want to test the third list view, but as it requires an intent the list returns nothing. To remedy this I can manually add the intent to the test which does mean it works
public InspectionListActivityTest() {
super(InspectionListActivity.class);
Intent i = new Intent();
i.putExtra("guid", "abcbbf2b-5e14-4cb1-af1b-e3084b45d4cf");
setActivityIntent(i);
}
As you can see from the code, it uses guids to determine the list which is what I want to avoid - I clear the database a lot while I'm testing so I have to change this field all of the time.
Ideally I want to use a ContentResolver to get the first guid from another table which would then mean I would be able to always pull back information in my tests, ie
public InspectionListActivityTest() {
super(InspectionListActivity.class);
ContentResolver cr = getActivity().getContentResolver();
Cursor cursor = cr.query(Locations.CONTENT_URI, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
String guid = cursor.getString(cursor.getColumnIndex(Locations.GUID));
Intent i = new Intent();
i.putExtra(IntentFilters.LOCATION.getIntent(), guid);
setActivityIntent(i);
}
}
}
However, I get a nullpointerexception on the getActivity() method, and I don't seem to be able to put this setActivityIntent anywhere else.
回答1:
This all should be done in the setup()
method of your test, not in its constructor. Constructors of tests are useless and should be kept unmodified.
回答2:
It can be done, but it's a bit messy. Basically got the guid from the database that I wanted, created a new intent to the original test class, attached the guid to the intent and then started the intent.
public void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
activity = getActivity();
UsefulFunctions.insertDummyData(getActivity());
ContentResolver cr = getActivity().getContentResolver();
Cursor cursor = cr.query(Locations.CONTENT_URI, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
guid = cursor.getString(cursor.getColumnIndex(Locations.GUID));
}
}
solo.goBack();
Intent i = new Intent(activity.getApplicationContext(), InspectionListActivity.class);
i.putExtra(IntentFilters.LOCATION.getIntent(), guid);
setActivityIntent(i);
activity.startActivity(i);
}
In a way, it was just easier to start on my first list and then get Robotium to 'click' in the list all the way to the screen that I wanted, i.e.
solo.clickInList(0);
// Locations
solo.clickInList(0);
ListView ls = solo.getCurrentListViews().get(0);
solo.waitForActivity("InspectionListActivity");
来源:https://stackoverflow.com/questions/15617173/using-robotium-with-intents