我正在尝试使用ActivityInstrumentationTestCase2测试AlertDialog.
这是原始代码:
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",int which) { InterventionImmobiliereDetailsActivity.this.lancerIntentAppel(mIntervention.getTelContact()); } }); mAdAppelerFixe = dialog.create(); mAdAppelerFixe.show(); } });
现在我无法点击正面按钮.此代码似乎不起作用:
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()); } });
首先,我单击我的布局以打开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(); }
这里的示例测试AlertDialog(来自android google source):
AlertDialogTest.java