I'm writing unit tests for a ListActivity in Android that uses a handler to update a ListAdapter. While my activity works in the Android emulator, running the same code in a unit test doesn't update my adapter: calls to sendEmptyMessage do not call handleMessage in my activity's Handler.
How do I get my ActivityUnitTestCase to sync with the MessageQueue thread and call my Handler?
The code for the Activity is somewhat like this:
public class SampleActivity extends ListActivity implements SampleListener {
List samples = new ArrayList();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_list);
listView.setEmptyView(findViewById(R.id.empty));
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// unit test never reaches here
sharesAdapter = new SampleAdapter(SampleActivity.this, samples);
setListAdapter(sharesAdapter);
}
};
public void handleSampleUpdate(SampleEvent event) {
samples.add(event.getSample());
handler.sendEmptyMessage(0);
}
}
The code for my unit test is somewhat like this:
public class SampleActivityTest extends ActivityUnitTestCase<SampleActivity> {
public SampleActivityTest() {
super(SampleActivity.class);
}
@MediumTest
public void test() throws Exception {
final SampleActivity activity = startActivity(new Intent(Intent.ACTION_MAIN), null, null);
final ListView listView = (ListView) activity.findViewById(android.R.id.list);
activity.handleSampleUpdate(new SampleEvent(this));
// unit test assert fails on this line:
assertTrue(listView.getCount() == 1);
}
}