Espresso で現在の表示アクティビティを取得して、それに応じて条件付きコードを書き留めることはできますか?
私のアプリケーションには、次のアプリケーションからユーザーを 1 回だけ表示する紹介ページがあり、ユーザーは直接ログイン画面に移動します。ユーザーがどの画面に到達したかを確認して、それに応じてテストケースを書き留めることができますか?
Espresso で現在の表示アクティビティを取得して、それに応じて条件付きコードを書き留めることはできますか?
私のアプリケーションには、次のアプリケーションからユーザーを 1 回だけ表示する紹介ページがあり、ユーザーは直接ログイン画面に移動します。ユーザーがどの画面に到達したかを確認して、それに応じてテストケースを書き留めることができますか?
チェックする必要があるレイアウトに一意の ID を入れることができます。あなたが説明した例では、ログインレイアウトに入れます:
<RelativeLayout ...
android:id="@+id/loginWrapper"
...
次に、テストでは、この ID が表示されていることを確認するだけです。
onView(withId(R.id.loginWrapper)).check(matches(isCompletelyDisplayed()));
より良い方法があるかどうかはわかりませんが、これはうまくいきます。
また、オンラインで見つけることができる waitId メソッドを使用して、しばらく待つこともできます。
/**
* Perform action of waiting for a specific view id.
* <p/>
* E.g.:
* onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15));
*
* @param viewId
* @param millis
* @return
*/
public static ViewAction waitId(final int viewId, final long millis) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}
@Override
public String getDescription() {
return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
}
@Override
public void perform(final UiController uiController, final View view) {
uiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + millis;
final Matcher<View> viewMatcher = withId(viewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
// found view with required ID
if (viewMatcher.matches(child)) {
return;
}
}
uiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
// timeout happens
throw new PerformException.Builder()
.withActionDescription(this.getDescription())
.withViewDescription(HumanReadables.describe(view))
.withCause(new TimeoutException())
.build();
}
};
}
このメソッドを使用すると、たとえば次のことができます。
onView(isRoot()).perform(waitId(R.id.loginWrapper, 5000));
このようにして、ログイン画面が表示されるまでに 5 秒以下かかる場合、テストは失敗しません。
私Espresso
が使用するテストクラスではActivityTestRule
、現在のアクティビティを取得するために使用します
mRule.getActivity()
これが私のコード例です:
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SettingsActivityTest {
@Rule
public ActivityTestRule<SettingsActivity> mRule = new ActivityTestRule<>(SettingsActivity.class);
@Test
public void checkIfToolbarIsProperlyDisplayed() throws InterruptedException {
onView(withText(R.string.action_settings)).check(matches(withParent(withId(R.id.toolbar))));
onView(withId(R.id.toolbar)).check(matches(isDisplayed()));
Toolbar toolbar = (Toolbar) mRule.getActivity().findViewById(R.id.toolbar);
assertTrue(toolbar.hasExpandedActionView());
}
}
それが役立つことを願っています