本篇先不寫Espresso 的環境配置,先來說下Espresso 的基本用法,我們知道UI測試是測試中的重要環節,但很多公司可能連單元測試都很少去測試,更別說UI自動化測試了,前段時間學習了下Espresso 自動化測試,下面我用代碼講解下:
1、我們先來最簡單的(判斷我們想要獲取的UI控件是否顯示在界面上)
onView(withId(R.id.tv_ok)).check(matches(isDisplayed()));
onView(withText("完成")).check(matches(isDisplayed()));
註釋:
withId 是根據id去獲取控件
withText是根據文字去獲取控件
.check(matches(isDisplayed())) 驗證是否在當前界面可見
2、 輸入框輸入文字
方式1、
onView(withId(R.id.et_text)).check(matches(isDisplayed()));
onView(withId(R.id.et_text)).perform(typeText("Hello"), closeSoftKeyboard()).check(matches(withText("Hello")));
typeText(“hello”)你看到是輸入框輸入hello的效果
closeSoftKeyboard 是取消軟鍵盤
check(matches(withText("Hello")) 判斷輸入框上的文字和hello是否一樣
方式2、
onView(withId(R.id.et_text)).check(matches(isDisplayed()));
onView(withId(R.id.et_text)).perform(replaceText("Hello"), closeSoftKeyboard()).check(matches(withText("Hello"));
方式1和方式2大家很明顯看到區別:withText(“Hello”)和replaceText("Hello");
這兩個在顯示除漢字外的都是一樣在輸入框上顯示內容一樣;
withText(“Hello”)是類似我們鍵盤輸入;
replaceText("Hello"); 是editText.setText(""); 輸入的過程我們根本看不到,只看到輸入框顯示了內容;
上面爲什麼說除漢字外在輸入框上顯示內容一樣,withText(“啊”)和replaceText("啊");不能表示嗎?
如果用
onView(withId(R.id.et_text)).perform(typeText("啊"), closeSoftKeyboard()).check(matches(withText("啊"));
ava.lang.RuntimeException: Failed to get key events for string 啊 (i.e. current IME does not understand how to translate the string into key events). As a workaround, you can use replaceText action to set the text directly in the EditText field.
也就是說withText(““”)不支持文字輸入,那麼我們用replaceText("");看看
onView(withId(R.id.et_text)).perform(replaceText("啊"), closeSoftKeyboard()).check(matches(withText("啊"));
上面的代碼就沒有問題;