我想点击AlertDialog
中的ActivityInstrumentationTestCase2
。但是DialogInterface.OnClickListener()
执行,测试结束后而不是在测试期间(我知道,因为我调试了这个测试)。
我的测试检查删除按钮。如果按下删除按钮,将出现AlertDialog
并再次询问用户。如果用户接受AlertDialog
,则将删除数据库行。
public class ShiftTest2 extends ActivityInstrumentationTestCase2<Shift> {
@UiThreadTest
public void testDeleteButton() {
Shift shift = getActivity();
Button deleteButton = (Button) shift.findViewById(R.id.shift_delete);
deleteButton.performClick(); // That works fine
AlertDialog alertDialog = shift.getAlertDialog();
// The thread execute the performClick() after this test finished
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
final Bundle savedShift = mDb.getShiftById("1");
assertNull(savedShift); // This assert fail
}
}
我的删除按钮OnClickListener
。
public void onDeleteButton(View view) {
if (mDeleteDialog != null) {
mAlert = mDeleteDialog.create();
mAlert.show();
}
}
这里是AlertDialog
的听众。
@Override
public void onCreate(Bundle savedInstanceState) {
...
mDeleteDialog = new AlertDialog.Builder(this);
mDeleteDialog.setMessage(getString(R.string.delete_shift_really));
mDeleteDialog.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mDb.deleteShift(mId);
resetAllPreferences();
Intent parentActivity = new Intent(context, WorkingTimeSettings.class);
startActivity(parentActivity);
}
});
mDeleteDialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Nothing to do here
}
});
}
我已经在测试中尝试了Thread.sleep(10000)
,但它没有任何改变。问题是,线程没有跳出测试来执行正按钮监听器。也许是因为@UiThreadTest
注释?