Espresso是一種UI Test自動化測試框架,可以在短時間跑完測試並且可以跟元件互動。
ActivityTestRule:取得Activity資源
先尋找元件再調用動作or檢查
尋找UI元件
onView(Matcher)
1.onView(withId()):利用ID。
2.onView(withText()):利用文字。
操作UI動作
perform(ViewActions)
1.perform(typeText()):輸入文字。
2.perform(click()):點擊。
3.perform(clearText()):清空文字。
檢查
check(ViewAssertion(Matcher))
1.check(matches(withId)):是否有這個ID
2.check(matches(withText)):是否有這個文字
3.check(matches(isDisplayed())):是否有顯示
build.gradle(Module)
dependencies {
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test:rules:1.3.0'
}
MainActivity.kt
val secret = Random().nextInt(20)
check.setOnClickListener {
if (secret == number.text.toString().toInt()) {
AlertDialog.Builder(this)
.setMessage("賓果")
.show()
} else {
AlertDialog.Builder(this)
.setMessage("沒猜中")
.setPositiveButton(getString(R.string.ok), null)
.show()
}
}
創建在(androidTest下)
MainActivityTest.kt
@RunWith(AndroidJUnit4ClassRunner::class)
class MainActivityTest {
@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
//測試方法
@Test
fun guessWrong() {
val resources = activityRule.activity.resources
val secret = activityRule.activity.secret
for (i in 0..19) {
if (i != secret) {
//清空文字
Espresso.onView(withId(R.id.number))
.perform(clearText())
//寫入文字
Espresso.onView(withId(R.id.number))
.perform(typeText(i.toString()))
//點擊按鈕
Espresso.onView(withId(R.id.check))
.perform(click())
//判斷文字有沒顯示
Espresso.onView(withText("沒猜中"))
.check(matches(isDisplayed()))
//按下Alert確認
Espresso.onView(withText(resources.getString(R.string.ok)))
.perform(click())
}
}
}
}