Android Junit Testing Of Preferences
A fairly normal scenario: an Android application has a preferences activity, and selecting an option from a ListPreference triggers code to change that ListPreference's summary tex
Solution 1:
A few more hours of work produced this working solution, but I'm curious if anyone else has a better solution. This code was inspired by this solution to a similar question, but this case is different in two ways:
- It's intended for use by Android JUnit, which means it needs to call the ListPreference UI clicks via
runOnUiThread()
. - It expects there to be preference categories in use, which complicate finding the position (relative to the entire preferences list) to click. The above mentioned solution only works in cases without preference categories.
This method will accept the key for a particular ListPreference item, along with the position of the item in the list to be clicked. It will then perform that list item click, and other code would do the checking I'm looking for.
Note that this requires setActivityInitialTouchMode(true);
to be set before the getActivity()
call in the setUp()
method.
privatevoidclickListPreference(String _listPreferenceKey, int _listItemPos){
finalStringlistPreferenceKey= _listPreferenceKey;
finalintlistItemPos= _listItemPos;
mActivity.runOnUiThread(
newRunnable() {
publicvoidrun() {
// get a handle to the particular ListPreference
ListPreference listPreference= (ListPreference) mActivity.findPreference(listPreferenceKey);
// bring up the dialog box
mActivity.getPreferenceScreen().onItemClick( null, null, getPreferencePosition(), 0 );
// click the requested itemAlertDialoglistDialog= (AlertDialog) listPreference.getDialog();
ListViewlistView= listDialog.getListView();
listView.performItemClick(listView, listItemPos, 0);
}
/***
* Finding a ListPreference is difficult when Preference Categories are involved,
* as the category header itself counts as a position in the preferences screen
* list.
*
* This method iterates over the preference items inside preference categories
* to find the ListPreference that is wanted.
*
* @return The position of the ListPreference relative to the entire preferences screen list
*/privateintgetPreferencePosition(){
intcounter=0;
PreferenceScreenscreen= mActivity.getPreferenceScreen();
// loop over categoriesfor (inti=0; i < screen.getPreferenceCount(); i++){
PreferenceCategorycat= (PreferenceCategory) screen.getPreference(i);
counter++;
// loop over category itemsfor (intj=0; j < cat.getPreferenceCount(); j++){
if (cat.getPreference(j).getKey().contentEquals(listPreferenceKey)){
return counter;
}
counter++;
}
}
return0; // did not match
}
}
);
getInstrumentation().waitForIdleSync();
}
Post a Comment for "Android Junit Testing Of Preferences"