So i have this test Activity with 3 elements: TextView, EditText, Button. When user clicks button, Activity then transforms text from EditText to some text in TextView.
Question is: how do i write unit test for such activity?
My problem: i should “click” (.performClick) on a button in one thread, but to wait asynchronously in another but that breaks a logic of a unit test since it runs every test starting with “test” prefix and marks test as “Ok” if there were no unsuccessful assertions.
Code of a unit test:
public class ProjectToTestActivityTest extends ActivityInstrumentationTestCase2<ProjectToTestActivity> {
private TextView resultView;
private EditText editInput;
private Button sortButton;
public ProjectToTestActivityTest(String pkg, Class activityClass) {
super("com.projet.to.test", ProjectToTestActivity.class);
}
public void onTextChanged(String str)
{
Assert.assertTrue(str.equalsIgnoreCase("1234567890"));
}
@Override
protected void setUp() throws Exception {
super.setUp();
Activity activity = getActivity();
resultView = (TextView) activity.findViewById(R.id.result);
editInput = (EditText) activity.findViewById(R.id.editInput);
sortButton = (Button) activity.findViewById(R.id.sortButton);
resultView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
onTextChanged(arg0.toString());
}
}
}
protected void testSequenceInputAndSorting()
{
editInput.setText("1234567890");
sortButton.performClick();
}
}
Suppose the business logic is properly implemented in your Activity under application project, in another word, when button is clicked, copy text from EditText to TextView.
how do i write unit test for such activity?
Update:
If you don’t use thread in your main application code, there is only UI thread in main application, all UI events (button clicked, textView updated and etc.) are processed continuously in UI thread, it is very unlikely that this continuous UI events will stuck/delay more than several seconds. If you are still no very sure, use waitForIdleSync() to make test application wait until no more UI events to process on main application’s UI thread:
However,
getInstrumentation().waitForIdleSync();will not wait for the thread spawned in your main application code, for instance, when click button, it starts AsyncTask process time-consuming job and after finish (say in 3 seconds), it updates the TextView, in this case, you have to useThread.sleep();to make you test application stop and wait, check out answer in this link for code example.