我正在为一个活动编写测试,该活动在发出和接收网络请求后显示确认对话框。我正在使用onView(withText(confirmText)).inRoot(isDialog()).check(matches(isDisplayed()));
来检查对话框,并且我还删除了inRoot()
来电,但无论我做什么,测试都挂在这里,永远不会完成。
我还为此活动添加了一个IdlingResource,当我收到一个成功的网络呼叫时,该活动被设置为空闲,但是否这是注册的似乎没什么区别。这似乎问题主要在于检查对话框。这是测试类:
@RunWith(AndroidJUnit4.class)
公共类RequestActivityTest {
private DialogFragmentIdlingResource mDialogFragmentIdlingResource;
private String mTestRequest;
private String mTopic;
@Rule
public ActivityTestRule<RequestActivity> mActivityTestRule = new ActivityTestRule<>(RequestActivity.class);
@Before
public void setUp() {
registerIdlingResource();
mTestRequest = "Test request";
mTopic = "Appliance";
}
@After
public void tearDown() {
unregisterIdlingResource();
}
@Test
public void enterText() {
onView(withId(R.id.request_input)).perform(typeText(mTestRequest));
}
@Test
public void checkMessageSent() {
mActivityTestRule.getActivity().setTopic(mTopic);
onView(withId(R.id.request_input)).perform(typeText(mTestRequest));
onView(withId(R.id.submit_request_button)).perform(click());
String confirmText = InstrumentationRegistry.getTargetContext().getString(R.string.confirm_request_dialog_message);
onView(withText(confirmText)).inRoot(isDialog()).check(matches(isDisplayed()));
}
public void registerIdlingResource() {
mDialogFragmentIdlingResource = (DialogFragmentIdlingResource) mActivityTestRule.getActivity().getIdlingResource();
Espresso.registerIdlingResources(mDialogFragmentIdlingResource);
}
public void unregisterIdlingResource() {
if (mDialogFragmentIdlingResource != null) {
Espresso.unregisterIdlingResources(mDialogFragmentIdlingResource);
}
}
}
以下是发送网络请求和注册空闲资源的Activity方法:
private void sendMessage() {
if (UserPreferences.getUserProfile().getCompanyProfile() != null) {
if (NetworkUtils.isConnectedToInternet(this)) {
if (mNetworkErrorMessageSnackbar != null) mNetworkErrorMessageSnackbar.dismiss();
String message = mRequestMessage.getText().toString();
mRequestPresenter.onRequestSubmit(UserPreferences.getUserProfile().getCompanyProfile()
.getBuilding().getId(), mTopic, message);
setFragmentIdle();
} else {
mNetworkErrorMessageSnackbar = new NetworkErrorMessageSnackbar
.Builder(HttpStatusCode.NO_INTERNET, mRequestLayout, this).build();
mNetworkErrorMessageSnackbar.show();
}
}
}
@VisibleForTesting
@NonNull
public IdlingResource getIdlingResource() {
if (mDialogFragmentIdlingResource == null) {
mDialogFragmentIdlingResource = new DialogFragmentIdlingResource(this.getSupportFragmentManager(), ConfirmationDialogFragment.TAG);
}
return mDialogFragmentIdlingResource;
}
public void setFragmentIdle() {
if (mDialogFragmentIdlingResource != null) {
mDialogFragmentIdlingResource.isIdleNow();
}
}
public void setTopic(String topic) {
mTopic = topic;
}