我试图测试MyActivity
显示一个警告对话框,当不正确的意图附加程序通过。这是一个网址,所以我通过网址到内部的webView加载网址,并显示一个警告,如果任何错误发生。当点击肯定按钮时应该解除警报。IdlingResource未在AndroidTests中等待
这是怎么当错误发生
// Method in `MyActivity.java` called when the url couldn't be loaded
private void showAlertDialog(final String title, final String message) {
final MyActivity self = this;
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isFinishing()) {
alertDialog = new AlertDialog.Builder(MyActivity.this)
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(BUTTON_OK_TITLE, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
self.alertDialog = null;
//self.finishWithMessage(messageRaw, true);
}
}).create();
alertDialog.show();
}
}
});
}
在测试中,我使用ElapsedTimeIdlingResource taken from chiuki's answer开展活动后,等待10秒,断言alertDialog创建和显示的alertDialog创建。
然后我按下提醒按钮,然后等待10秒,试图断言它不见了。
这是测试代码MyActivityTest.java
:
@RunWith(AndroidJUnit4.class)
public class MyActivityTest {
@Rule
public ActivityTestRule<MyActivityTest> mActivityRule = new ActivityTestRule<>(MyActivityTest.class, true, false);
@Test
public void testErrorDialog() {
Intent intent = createIntentWithWrongExtras();
mActivityRule.launchActivity(intent);
// Wait
IdlingResource idlingResource1 = new ElapsedTimeIdlingResource(10000);
Espresso.registerIdlingResources(idlingResource1);
assertNotNull("Activity should have been created", mActivityRule.getActivity());
assertNotNull("AlertDialog should have been created", mActivityRule.getActivity().alertDialog);
assertTrue("AlertDialog should be showing", mActivityRule.getActivity().alertDialog.isShowing());
// Test clicking the button dismisses the alert
mActivityRule.getActivity().runOnUiThread(() ->
mActivityRule.getActivity().alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick()
);
IdlingResource idlingResource2 = new ElapsedTimeIdlingResource(10000);
Espresso.registerIdlingResources(idlingResource2);
assertTrue("AlertDialog should NOT be showing", mActivityRule.getActivity().alertDialog == null || !mActivityRule.getActivity().alertDialog.isShowing());
Espresso.unregisterIdlingResources(idlingResource2);
}
}
然而,测试总是失败:
“AlertDialog不应该被显示”
我不认为我是很好地理解到底发生了什么。我写了一些日志,我可以看到idlingResource1
从不等待10秒钟。另外我知道alertDialog在被解散时变为空,但发生在最后一个断言后,所以idlingResource2
也不起作用?为什么?这是测试这个的正确方法吗?