[英]What is the best way to await functions in UI testing in Android Studio without Thread.Sleep()?
我正在使用 Espresso 為我開發的 Android 應用程序編寫一些自動化測試。 所有測試都是自動化的,並且根據 UI 發生的情況來通過/失敗。 我已經通過 SonarQube 運行代碼以檢測不良編碼實踐,並告知我不應使用 Thread.Sleep()。
我主要在輸入表單並需要隱藏鍵盤以向下滾動以點擊下一個表單字段等的情況下使用 Thread.sleep()。據我了解,使用諸如等待功能之類的東西適用於大型異步功能像獲取數據等,但是在我的情況下我應該使用什么東西沒有被獲取但更多的是用於與 UI 交互?
這是我創建的使用 Thread.Sleep() 的登錄測試示例:
onView(withId(R.id.fieldEmail)).perform(typeText("shelley@gmail.com"));
Thread.sleep(SHORT_WAIT);
onView(withId(R.id.fieldPassword)).perform(click());
onView(withId(R.id.fieldPassword)).perform(typeText("password"));
Thread.sleep(SHORT_WAIT);
onView(isRoot()).perform(pressBack());
Thread.sleep(SHORT_WAIT);
onView(withId(R.id.signIn)).perform(click());
Thread.sleep(LONG_WAIT);
有幾種選擇:
您可以使用Awaitility重復重試斷言/檢查,直至指定的時間允許:
應用程序/build.gradle
dependencies {
// Note: Awaitility version 4 has dependency conflicts with JUnit's
// Hamcrest. See: https://github.com/awaitility/awaitility/issues/194
androidTestImplementation 'org.awaitility:awaitility:3.1.6'
}
// Set the retry time to 0.5 seconds, instead of the default 0.1 seconds
Awaitility.setDefaultPollInterval(500, TimeUnit.MILLISECONDS);
Kotlin:
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted {
onView(withId(R.id.fieldPassword)).perform(click())
}
Java 7:
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(new ThrowingRunnable() {
@Override
public void run() throws Throwable {
onView(withId(R.id.fieldPassword)).perform(click());
}
});
這意味着如果斷言第一次失敗,它將重試最多 2 秒,直到它為true
或發生超時( fail
)。
您還可以在進行第一個斷言之前設置初始時間延遲:
Awaitility.await().pollDelay(1, TimeUnit.SECONDS).atMost(3, TimeUnit.SECONDS).untilAsserted {
onView(withId(R.id.fieldPassword)).perform(click())
}
或者,您可以在語句之間添加簡單的時間延遲,就像Thread.sleep()
一樣,但以更詳細的方式:
Kotlin:
Awaitility.await().pollDelay(2, TimeUnit.SECONDS).until { true }
Java 7:
Awaitility.await().pollDelay(2, TimeUnit.SECONDS).until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return true;
}
});
一般注意事項:雖然在單元測試中通常應避免使用Thread.sleep()
或其他一些時間延遲,但有時您需要使用它,並且沒有其他選擇。 一個示例是使用IntentsTestRule
在您的應用程序中單擊 web 鏈接以啟動外部 web 瀏覽器。 您不知道瀏覽器需要多長時間才能啟動 web 頁面,因此您需要添加一個時間延遲。
關於等待的更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.