Testing ListView with Robolectric

android, android-listview, robolectric

Solution

If people like me, still visiting the link to resolve how to test listview with Roboelectric 3.0. This is my MAinActivityTest file

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());
}

RowModel is the simple POJO for fields to be displayed in listview.

Problem

I'm currently trying to test some Android Code with Robolectric but I'm having some issues with my ListView. When I try to access the a child view, ListView always return null, due to an empty List. The implementation of the application 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'm trying to access my ListView as following. The Robolectric TestRunner always return null when I'm accessing the ArrayAdapter through 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"); } } ```

Original source