android - 如何为 AlertDialog 进行 Robolectric 测试

标签 android robolectric

我是 robolectric 的新手,我正在尝试对创建 AlertDialog 的按钮进行测试。单击该按钮时,会生成一个带有正按钮的 AlertDialog,我想使用 Robolectric 单击该按钮,并测试它是否启动 Activity 。这是按钮的代码:

newUserButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
            builder.setTitle(context.getResources().getString(R.string.start_title_message))
                    .setMessage(getResources().getString(R.string.start_dialog_message));
            builder.setPositiveButton(getString(R.string.start_confirm_message), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    startActivityForResult(new Intent(StartActivity.this, AvatarRoomActivity.class), 0);
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();
            ColorDrawable drawable = new ColorDrawable(Color.WHITE);
            drawable.setAlpha(200);
            dialog.getWindow().setBackgroundDrawable(drawable);
            dialog.show();
        }
    });

有谁知道我如何测试单击肯定按钮,然后启动 AvatarRoomActivity?在此先感谢并希望很快收到某人的来信。

最佳答案

我今天遇到了这个问题,不建议仅仅为了测试而公开一个私有(private)函数。

Robolectric 提供了一个ShadowAlertDialog,它可以检测显示的DialogAlertDialog

//get all shown dialogs    
ShadowAlertDialog.getShownDialogs()

//get single dialog  
(ShadowAlertDialog.getLatestDialog() as android.support.v7.app.AlertDialog)
    .getButton(AlertDialog.BUTTON_POSITIVE)
    .performClick()

//Continue the test

关于android - 如何为 AlertDialog 进行 Robolectric 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47655855/

相关文章:

java - 我正在研究 Robolectric 但出现错误

android - 创建具有可点击图像的 Gridview,Android

java - 从另一个类访问 MainActivity 对象

android - 如何在Youtube Player-API中播放多个视频?

android - Robolectric = Mockito : Cannot Create Mock or Spy In Mockito Because: dexcache == null

android - Robolectric 3.0,未能测试启动 HandlerThread 的函数

android - Robolectric 3 中带有 Play 服务的异步测试代码

android - 无法在 Android 模拟器上安装 ARCore

android - 清除 RecyclerView 行中的 EditText 值

android - Robolectric 3.1 中缺少 ShadowViewTreeObserver