Lyn*_*nal 6 android unit-testing click button android-alertdialog
我正试图测试AlertDialog一下ActivityInstrumentationTestCase2.
这是原始代码:
this.setmBtAppelerFixe(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog = new AlertDialog.Builder(InterventionImmobiliereDetailsActivity.this);
dialog.setTitle("Appel");
dialog.setMessage("Appeler le contact ?");
dialog.setCancelable(true);
dialog.setNegativeButton("Non", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
InterventionImmobiliereDetailsActivity.this.lancerIntentAppel(mIntervention.getTelContact());
}
});
mAdAppelerFixe = dialog.create();
mAdAppelerFixe.show();
}
});
Run Code Online (Sandbox Code Playgroud)
现在我无法点击正面按钮.此代码似乎不起作用:
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
assertTrue(mLLAppelerFixe.performClick());
AlertDialog mDialog = mActivity.getAdAppelerFixe();
assertTrue(mDialog.isShowing());
Button okButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
assertTrue(okButton.performClick());
assertTrue(mActivity.isNumeroValide());
}
});
Run Code Online (Sandbox Code Playgroud)
首先,我点击我的布局打开AlertDialog.然后我得到了OK_BUTTON,然后点击它.它应该将numeroValide布尔值设置为true.但没什么.
我怎样才能简单地AlertDialog用按钮测试?
这在我的 Nexus 4 设备中完美运行:
@MediumTest
public void testStartMyActivity() {
monitor = getInstrumentation().addMonitor(MyActivity.class.getName(), null, false);
TouchUtils.clickView(this, startMyActivityButton);
MyActivity myActivity = (MyActivity) monitor.waitForActivityWithTimeout(2000);
assertNotNull("MyActivity activity not started, activity is null", myActivity);
AlertDialog dialog = myActivity.getLastDialog(); // I create getLastDialog method in MyActivity class. Its return last created AlertDialog
if (dialog.isShowing()) {
try {
performClick(dialog.getButton(DialogInterface.BUTTON_POSITIVE));
} catch (Throwable e) {
e.printStackTrace();
}
}
myActivity.finish();
getInstrumentation().removeMonitor(monitor);
}
private void performClick(final Button button) throws Throwable {
runTestOnUiThread(new Runnable() {
@Override
public void run() {
button.performClick();
}
});
getInstrumentation().waitForIdleSync();
}
Run Code Online (Sandbox Code Playgroud)
这里是测试 AlertDialog 的示例(来自 android google 源代码): AlertDialogTest.java