user138439
user138439

Reputation:

How to test a ListActivity?

I'm new to Android development as well as test-driven development. I want to write unit tests for the following ListActivity:

public class TrendsMainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    String[] list_items = getResources().getStringArray(R.array.trend_menu_names);
    setListAdapter(new ArrayAdapter<String>(this, R.layout.main, list_items));
}

@Override
protected void onListItemClick(ListView listView, View view, int position, long id)
{
    Intent intent = null;

    switch(position)
    {
        case 0:
            intent = new Intent(this, TrendingActivity.class);
            break;
        case 1:
            intent = new Intent(this, SearchActivity.class);
            break;
        case 2:
            intent = new Intent(this, TimelineActivity.class);
            break;
    }
    if(intent != null)
    {
        startActivity(intent);
    }
    else
    {
        Log.e(getClass().getSimpleName(), "There was an error retrieving request.");
    }
}}

I have scoured all of the documentation that I can find, but I can not figure out how to test this Activity. The onListItemClick method is not finished, but it gives the idea of what I want to accomplish. I want to test clicking the first item in the ListView, and test that the correct Activity is being started.

How can I accomplish this?

Edit: I want my test to "click" on an item in the ListView. I then want to assert that the activity started is the correct activity (e.g. Clicking ListView item 0 starts the TrendingActivity specifically)

Upvotes: 1

Views: 2834

Answers (1)

Diego Torres Milano
Diego Torres Milano

Reputation: 69368

I should say that if you were applying TDD you should have started writing the tests not the application.

Anyway, Android Application Testing Guide contains in chapter 3 two examples that combined together can give you the solution you are looking for. The idea is to use an ActivityMonitor to verify that the expected activity was started.

@UiThreadTest
public void testListItemClickStartsActivity() {
    final Instrumentation inst = getInstrumentation();
    final IntentFilter intentFilter = new IntentFilter();
    // here add conditions to your filter, i.e. intentFilter.addAction()
    ActivityMonitor monitor = inst.addMonitor(intentFilter, null, false);
    assertEquals(0, monitor.getHits());
    // here perform desired click on list
    monitor.waitForActivityWithTimeout(5000);
    assertEquals(1, monitor.getHits());
    inst.removeMonitor(monitor);
}

Upvotes: 4

Related Questions