可以使用Espresso的IdlingResource API来等待对话框的出现。下面是示例代码:
首先,创建一个名为DialogUtils的工具类,用于等待对话框的出现:
import android.app.Activity;
import android.app.Dialog;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.IdlingResource.ResourceCallback;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import androidx.test.runner.lifecycle.Stage;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
public class DialogUtils {
private static final String DIALOG_FRAGMENT_TAG = "androidx.fragment.app.DialogFragment";
private static final String DIALOG_TAG = "android.app.Dialog";
public static IdlingResource waitForDialogToBeDisplayed() {
return new WaitDialogIdlingResource();
}
private static class WaitDialogIdlingResource implements IdlingResource {
private final AtomicBoolean mIsIdleNow = new AtomicBoolean(true);
private ResourceCallback mResourceCallback;
@Override
public String getName() {
return WaitDialogIdlingResource.class.getName();
}
@Override
public boolean isIdleNow() {
boolean isIdle = isDialogDisplayed();
if (isIdle) {
mIsIdleNow.set(true);
if (mResourceCallback != null) {
mResourceCallback.onTransitionToIdle();
}
}
else {
mIsIdleNow.set(false);
}
return mIsIdleNow.get();
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
mResourceCallback = callback;
}
private boolean isDialogDisplayed() {
Collection resumedActivities =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
for (Activity activity : resumedActivities) {
if (activity != null) {
if (activity instanceof androidx.fragment.app.FragmentActivity) {
androidx.fragment.app.FragmentManager fragmentManager = ((androidx.fragment.app.FragmentActivity)activity)
.getSupportFragmentManager();
if (fragmentManager.findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) {
return true;
}
}
if (activity.getWindow() != null) {
Dialog dialog = activity.getWindow().peekDecorView() instanceof Dialog ? (Dialog) activity.getWindow().peekDecorView() : null;
if (dialog != null && dialog.isShowing()) {
return true;
}
if (activity.getFragmentManager() != null) {
DialogFragment dialogFragment = (DialogFragment) activity.getFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_TAG);
if (dialogFragment != null && dialogFragment.getShowsDialog() && dialogFragment.getDialog().isShowing()) {
return true;
}
}
}
}
}
return false;
}
}
}
然后,在测试代码中,使用以下代码等待对话框出现:
@Test
public void testDialogDisplayed() {
//点击一个按钮打开一个对话框
Es