How do I get a View from a Preference in an ActivityInstrumentationTestCase?

2,125 views
Skip to first unread message

Brian Cavagnolo

unread,
Mar 27, 2009, 5:47:19 PM3/27/09
to android-...@googlegroups.com
Hello,

I'm trying to create an instrumentation test for a PreferenceActivity. I'm
able to get references to the PreferenceScreen and the individual Preference
objects in that screen. However, I can't seem to figure out how to get the
View associated with a particular Preference so I can click it. The examples
I've seen use the activity's findViewById method to get a view, but the xml
that specifies the Preference objects doesn't have ids.

The Preference object does have a getView method, which sounds very promising.
However, I can't figure out what to pass for its convertView and parent
arguments. Please advise. Here's the code so far:

public class MyPreferenceActivityTest extends
ActivityInstrumentationTestCase<MyPref> {

MyPref mActivity = null;

public MyPreferenceActivityTest() {
super("com.android.settings", MyPref.class);
}

@Override
public void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
}

public void testEnable() throws Exception {
final PreferenceScreen preferenceScreen =
mActivity.getPreferenceScreen();
assertTrue(preferenceScreen != null);
final Preference enabler = mActivity.findPreference("my_enabler");
assertTrue(enabler != null);
// This is my best guess so far, but it doesn't work :(
View view = enabler.getView(null, mActivity.getListView());
assertTrue(view != null);
TouchUtils.clickView(this, view);
Thread.sleep(3000);
assertTrue(true);
}
}

Brian Cavagnolo

unread,
Mar 27, 2009, 8:26:58 PM3/27/09
to android-...@googlegroups.com
I (kinda) figured this out. I think the solution is a bit of a hack, but here
it is anyhow. Improvements welcome:

public class MyPreferenceActivityTest extends
ActivityInstrumentationTestCase<MyPref> {

MyPref mActivity = null;

public MyPreferenceActivityTest() {
super("com.android.settings", MyPref.class);
}

@Override
public void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
}

public void testEnableConnectDisconnect() throws Exception {


final PreferenceScreen preferenceScreen =
mActivity.getPreferenceScreen();
assertTrue(preferenceScreen != null);
final Preference enabler = mActivity.findPreference("my_enabler");
assertTrue(enabler != null);

ListView list = mActivity.getListView();
for (int i=0; i < list.getChildCount(); i++) {
if (list.getItemAtPosition(i).equals(enabler)) {
TouchUtils.clickView(this, list.getChildAt(i));
Thread.sleep(3000);
}
}
assertTrue(true);

Reply all
Reply to author
Forward
0 new messages