android – 如何为AlertDialog进行Robolectric测试
作者:互联网
我是robolectric的新手,我正在尝试对创建AlertDialog的按钮进行测试.单击该按钮时,将使用正面按钮创建一个AlertDialog,我想使用Robolectric单击该按钮,并测试它是否启动了一个活动.这是按钮的代码:
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?提前致谢,希望很快能收到某人的来信.
解决方法:
让我们暂时忘记newUserButton.它与问题无关.
您需要公开AlertDialog对象,以便可以在单元测试代码中访问它.所以我假设你的活动在StartActivity中有这样的方法:
AlertDialog showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
builder.setTitle("This is title")
.setMessage("Dialog Message");
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivityForResult(new Intent(this, AvatarRoomActivity.class), 0);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
return dialog;
}
然后newUserButton的click事件只是调用此方法.
然后我们有这样的测试用例:
@Test
public void testLaunchAvatarRoomWhenConfirm() {
StartActivity startActivity = Robolectric.buildActivity(StartActivity.class).create().get();
AlertDialog dialog = startActivity.showDialog();
// Key part 1 : simulate button click in unit test
Button confirm = dialog.getButton(Dialog.BUTTON_POSITIVE);
confirm.performClick();
// Key part 2 : Check that startActivityForResult is invoke
ShadowActivity shadowActivity = shadowOf(startActivity);
ShadowActivity.IntentForResult intentForResult = shadowActivity.getNextStartedActivityForResult();
// assert that the proper request to start activity is sent
ComponentName nextActivity = intentForResult.intent.getComponent();
assertEquals(".AvatarRoomActivity", nextActivity.getShortClassName());
}
此测试方法验证当单击对话框的正按钮时,将使用适当的活动类名调用startActivityForResult.
所以剩下的问题是我们如何确保活动真正得到解决和启动.通常我会在此时停止测试警报对话框操作.是否可以解决意图并启动活动属性超出了此特定测试用例的范围.
标签:android,robolectric 来源: https://codeday.me/bug/20190823/1698336.html