我试着写一个小应用程序和相关的单元测试。
我有一个ListView绑定到SimpleCursorAdapter读取SQL表中的数据。
Activity#onCreate()方法是:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(this);
SQLiteDatabase dbRead = dbHelper.getReadableDatabase();
String[] columns={BaseColumns._ID, ENTRY_VALUE};
cursor = dbRead.query(ENTRIES_TABLENAME, columns, null, null, null, null, null);
String[] from = {"value"};
int[] to = {R.id.value};
adapter = new SimpleCursorAdapter(this, R.layout.list_entry, cursor, from, to);
setListAdapter(adapter);
}
我在单元测试中的测试是:
@UiThreadTest
public void testTheElementInsideTheDBisDisplayedInTheList() {
String entryValue = "clipboard entry 1";
DatabaseHelper dbHelper = new DatabaseHelper(cmActivity);
Cursor beforeCursor = selectAllEntries(dbHelper);
// The table, at the begining of the test, is empty, I control that
assertEquals(0, beforeCursor.getCount());
// I insert the new value in the table
insertEntry(dbHelper, entryValue);
// and I control that is really inside the table now
Cursor afterCursor = selectAllEntries(dbHelper);
assertEquals(1, afterCursor.getCount());
// This method calls the method "requery()" on the cursor associate
// to the listView's adapter to update the list view
cmActivity.updateList();
// I control that the listView is updated
assertEquals(1, entryList.getCount());
// Now I try to retrive the only child inside the list view
// to extract the text inside it and to compare this text with
// the value inserted into the DB table.
TextView entryView = (TextView) entryList.getChildAt(0);
String viewText = entryView.getText().toString();
assertEquals(entryValue, viewText);
}
我的问题出在第三行:
TextView entryView = (TextView) entryList.getChildAt(0);
我sude getChildAt()来获取ListView的第一个TextView子项。但是此方法返回null,因此测试会获得NullPointerException。
也许getChildAt()不是从ListView获取View子进程的正确方法,所以哪个是正确的?
我从文档中看到该方法适用于GroupView,我没有使用它们,我是否需要配置默认的GroupView并将所有条目放入其中?这样,getChildAt(0)会工作吗?这是设置ListView的正确方法吗?
谢谢你,再见
安德里亚
正如Vivek所问,我在这里发布了main.xml:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Empty set"
/>
你可以看到非常非常基本的。另外列表条目非常简单:
android:id="@+id/value"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >