我已经实现了一个在单击列表项时ListView
启动一个新的。Activity
当我手动测试它时,它工作得很好。但是当我尝试使用 进行自动化测试时ActivityUnitTestCase
,我得到的NullPointerException
好像ListView
是空的。
MainActivity(部分):
public class MainActivity extends ListActivity {
@Override
protected void onResume() {
super.onResume();
String[] items = new String[] {"item 1", "item 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener () {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView clickedItem = (TextView) view;
CharSequence clickedItemText = clickedItem.getText(); // throws a NullPointerException when running testWithPerformItemClick()!
Intent intent = new Intent(MainActivity.this, ItemDisplayActivity.class);
intent.putExtra("parameter", clickedItemText);
startActivity(intent);
}
});
}
}
失败的测试代码:
public class MainActivityTest extends ActivityUnitTestCase<MainActivity> {
ListView listView;
View child0;
public MainActivityTest() {
super(MainActivity.class);
}
private void setUpTest() {
MainActivity activity = startActivity(new Intent(), null, null);
getInstrumentation().callActivityOnStart(activity);
getInstrumentation().callActivityOnResume(activity);
listView = (ListView) activity.findViewById(android.R.id.list);
child0 = listView.getChildAt(0); // returns null!
}
public void testWithPerformClick() {
setUpTest();
child0.performClick(); // throws a NullPointerException!
Intent startedIntent = getStartedActivityIntent();
assertEquals("item 1", startedIntent.getStringExtra("parameter"));
}
public void testWithPerformItemClick() {
setUpTest();
long itemId = listView.getAdapter().getItemId(0);
listView.performItemClick(child0, 0, itemId); // throws a NullPointerException!
Intent startedIntent = getStartedActivityIntent();
assertEquals("item 1", startedIntent.getStringExtra("parameter"));
}
两种测试方法都失败,因为listView.getChildAt(0)
返回null
. 为什么是ListView
空的?我怎样才能强迫它用正确的孩子更新自己?