web-dev-qa-db-ja.com

Espresso-非同期でロードされたデータを使用してTextViewをアサートする

Google Espressoを使用してAndroidのUIテストを作成していますが、Webサービスから非同期に読み込まれるコンテンツであるTextViewテキストをアサートする方法に固執しています。現在のコードは次のとおりです。

public class MyTest extends BaseTestCase<MyActivity>{
    public void setUp() throws Exception {
        // (1) Tell the activity to load 'element-to-be-loaded' from webservice
        this.setActivityIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("data://data/element-to-be-loaded")));
        getActivity();

        super.setUp();
    }

    public void testClickOnReviews(){
        // (2) Check the element is loaded and its name is displayed
        Espresso
            .onView(ViewMatchers.withId(R.id.element_name))
            .check(ViewAssertions.matches(ViewMatchers.withText("My Name")));

        // (3) Click on the details box
        Espresso
            .onView(ViewMatchers.withId(R.id.details_box))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
            .perform(ViewActions.click());

        // (4) Wait for the details screen to open
        Espresso
            .onView(ViewMatchers.withId(R.id.review_box));

        // Go back to element screen
        Espresso.pressBack();
    }
}

(1)で、Webサービスから要素をロードするようにアクティビティに通知します。 (2)では、その内容を主張するビューを待っています。これは、Webサービスがアプリに応答する前に実行されるため、テストが失敗する部分です。

特定のデータが画面に表示されるのを待つようにEspressoに指示するにはどうすればよいですか?それとも、そのようなテストを書くために別の方法で考える必要がありますか?

14
Bolhoso

このケースを処理するには、WebサービスのIdlingResourceをEspressoに登録します。この記事を見てください: https://developer.Android.com/training/testing/espresso/idling-resource.html

ほとんどの場合、 CountingIdlingResource (単純なカウンターを使用して何かがアイドル状態になったことを追跡します)を使用することをお勧めします。この サンプルテスト は、これを行う方法を示しています。

19
ValeraZakharov

EspressoでUiAutomatorを使用することに悩まされていない場合は、ステップ4で次のようなことを行うことができます。

UiObject object = mDevice.findObject(new UiSelector().resourceId(packageName + ":id/" + "review_box"));
object.waitForExists(5000);

https://developer.Android.com/reference/Android/support/test/uiautomator/UiObject.html#waitForExists(long)

1
aestheticfish