Android活动单元测试用例中的测试对话框

时间:2010-03-02 18:13:38

标签: android unit-testing

我正在尝试在android中测试一个Activity,它将显示一个ProgressDialog并且在App中一切正常,但是当我尝试使用ActivityUnitTestCase并且测试导致Activity显示对话框失败时出现此错误:< / p>

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRoot.setView(ViewRoot.java:429)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:178)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:392)

我正在查看问题,当我们尝试从测试中创建它时,我的活动的onCreateDialog方法似乎崩溃了,我认为这是另一个上下文,我明白了,不过我想知道你们中的任何一个成功尝试这样的场景。

这是我的onCreateDialog的代码。

    public Dialog onCreateDialog(final int id)
{
    Dialog dialog;
    switch (id)
    {
        case PROGRESS_BAR:
            loadingDialog = new ProgressDialog(this);
            loadingDialog.setMessage("searching for product...");
            loadingDialog.setIndeterminate(true);
            dialog = loadingDialog;
            break;
        case INEXISTING_PRODUCT:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Product not found");
            builder.setPositiveButton("OK", null);
            dialog = builder.create();
            break;
        case UNAVAILABLE_SERVICE:
            AlertDialog.Builder unavailableBuilder = new AlertDialog.Builder(this);
            unavailableBuilder.setMessage("Service Unavailable");
            unavailableBuilder.setPositiveButton("OK", null);
            dialog = unavailableBuilder.create();
            break;
        default:
            dialog = super.onCreateDialog(id);
    }
    return dialog;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我相信,我找到了办法。

问题是我需要从ActivityInstrumentationTestCase2扩展,并且这样做是为了避免GUI线程出现问题。

  final Button uButton = (Button) activity.findViewById(R.id.btnSearchProduct);
    activity.runOnUiThread(new Runnable()
    {
        public void run()
        {
            uButton.performClick();
        }
    });

我唯一的问题是如何检查结果,因为我需要检查我登陆的活动及其附加内容?

相关问题