ei.*_*ken 4 android android-listview robolectric
我目前正在尝试使用Robolectric测试一些Android代码,但我的ListView存在一些问题.当我尝试访问子视图时,由于列表为空,ListView始终返回null.
应用程序的实现如下所示,并创建一个简单的列表视图:
private ListView listView;
private ArrayAdapter<String> adapter;
private static String values[] =
new String[] {"Android", "Apple", "Windows" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
initialize();
}
private void initialize() {
listView = (ListView) findViewById(R.id.tweet_list);
adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1,
values);
listView.setAdapter(adapter);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试访问我的ListView时,如下所示.当我通过getChildAt()访问ArrayAdapter时,Robolectric TestRunner始终返回null
private OverviewActivity activity;
private ListView listView;
@Before
public void setUp() throws Exception {
activity = new OverviewActivity();
activity.onCreate(null);
listView = (ListView) activity.findViewById(R.id.tweet_list);
}
@Test
public void shouldFindListView() throws Exception {
if (listView.getChildCount() > 0) {
assertThat(
"Android",
equalTo(listView.getChildAt(0).toString()));
} else {
fail("no child views are avaliable");
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人喜欢我,仍然访问链接以解决如何使用Roboelectric 3.0测试listview.这是我的MAinActivityTest文件
private MainActivity mainActivity;
private ListView lstView;
@Before
public void setup() throws Exception{
mainActivity= Robolectric.setupActivity(MainActivity.class);
assertNotNull("Mainactivity not intsantiated",mainActivity);
lstView=(ListView)mainActivity.findViewById(R.id.list);//getting the list layout xml
ShadowLog.stream = System.out; //This is for printing log messages in console
}
@Test
public void shouldFindListView()throws Exception{
assertNotNull("ListView not found ", lstView);
ShadowListView shadowListView = Shadows.shadowOf(lstView); //we need to shadow the list view
shadowListView.populateItems();// will populate the adapter
ShadowLog.d("Checking the first country name in adapter " ,
((RowModel)lstView.getAdapter().getItem(0)).getCountry());
assertTrue("Country Japan doesnt exist", "Japan".equals(((RowModel) lstView.getAdapter().getItem(0)).getCountry()));
assertTrue(3==lstView.getChildCount());
}
Run Code Online (Sandbox Code Playgroud)
RowModel是要在listview中显示的字段的简单POJO.