When testing the Android user interface, how can I wait until the user interface is ready?

The test looks like this (it ActivityInstrumentationTestCase2):

public void testItShowsThreeRows() { activity = getActivity(); activity.runOnUiThread(new Runnable() { public void run() { AccountsList accountsList = new AccountsList(activity, accounts); list.show(); } }); ListView listView = (ListView)activity.findViewById(R.id.list); assertEquals(3, listView.getChildCount()); } 

The code I'm trying to verify works. But the test fails because activity.runOnUiThread returns immediately. I can insert Thread.sleep and the test turns green, but for me it looks pretty awkward. Should I use some thread synchronization or maybe there is a poll for some user interface element to be ready?

I tried to annotate it with @UiThreadTest , but that won't work either. The code in list.show() populates the ListView through the user adapter, and getView is called in another thread (none of them are executed), and I have nothing to do with it, I have neither threads, nor async, nor anything), The test failed again as it returns before the user interface is ready for verification.

+8
android testing
source share
2 answers

You need to do Thread.sleep. I donโ€™t think there is a way around this. I do not understand why this is "awkward"; you are doing a test, so you need to wait for the system to show the user interface element that you want to test.

It seems to me that you are really trying to check the AccountsList or list. There is little reason to check ListView or findViewById if you are not paranoid.

You should focus on testing the AccountsList and user adapter. You do not need to use the user interface for this.

+4
source share

Calling waitForIdleSync () is better than sleeping for a fixed time.

+9
source share

All Articles