我正在使用Espresso測試Android應用程序。我有一個EditText
小工具與androidInputType=date
。當我用手指觸摸此控件時,會彈出一個日曆以選擇日期。從Android中的日曆中選擇日期Espresso
如何在Espresso中自動執行此操作?我看遍了所有的地方,我無法弄清楚。 typeText()
肯定不起作用。
我正在使用Espresso測試Android應用程序。我有一個EditText
小工具與androidInputType=date
。當我用手指觸摸此控件時,會彈出一個日曆以選擇日期。從Android中的日曆中選擇日期Espresso
如何在Espresso中自動執行此操作?我看遍了所有的地方,我無法弄清楚。 typeText()
肯定不起作用。
由本人原創回答在這裏,但在另一個問題範圍:Recording an Espresso test with a DatePicker - 所以我轉貼我的改編回答有:
使用此行來設置日期在日期選擇器:
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
這使用了作爲意式咖啡支持庫的一部分的PickerActions
- espresso-contrib
。要使用它,像這樣把它添加到您的gradle這個文件(你需要幾個排除,防止編譯錯誤,由於不匹配支持庫版本):
androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
exclude group: 'com.android.support', module: 'appcompat'
exclude module: 'support-annotations'
exclude module: 'support-v4'
exclude module: 'support-v13'
exclude module: 'recyclerview-v7'
exclude module: 'appcompat-v7'
}
然後,你可以創建一個輔助方法,點擊打開的視圖日期選擇器,設置日期和點擊確定按鈕證實了這一點:
public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
onView(withParent(withId(buttonContainer)), withId(datePickerLaunchViewId)).perform(click());
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
onView(withId(android.R.id.button1)).perform(click());
}
,然後用它像這樣在你的測試:
TestHelper.setDate(R.id.date_button, 2017, 1, 1);
//TestHelper is my helper class that contains the helper method above
我不得不將「2.2.2」替換爲「2.2」以避免構建衝突。 – Hack06
可以顯示的ID和它們的數據類型。您需要點擊的日曆ID。 –
剛纔看到我的答案似乎也幫助其他人。如果它解決了你的問題,如果你能接受它作爲一個正確的答案會很好。 – stamanuel