gpt4 book ai didi

android - 如何在 Android 中测试 AlertDialog?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:12 24 4
gpt4 key购买 nike

我正在尝试使用 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", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, 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 bool 值设置为 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 源): AlertDialogTest.java

关于android - 如何在 Android 中测试 AlertDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17526005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com