I'm currently trying to test Android code with Robolectric, but I'm having some problems with my ListView. When I try to access a child view, the ListView always returns null due to an empty list.
The application implementation looks like this and creates a simple list view:
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); }
However, when I try to access my ListView, as shown below. Robolectric TestRunner always returns null when I access the ArrayAdapter via getChildAt ()
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"); } }
source share