AndroidJUnitRunner 类是一个 JUnit 测试运行程序,可让您在 Android 设备上运行 JUnit 3 或 JUnit 4 型测试类,包括使用 Espresso 和 UI Automator 测试框架的测试类。
此测试运行程序负责将测试软件包和被测应用加载到设备上,运行测试并报告测试结果。此类将替换
此测试运行程序支持几项常见的测试任务,包括以下各项:
编写 JUnit 测试
此测试运行程序与 JUnit 3 和 JUnit 4(最高为 JUnit 4.10)测试兼容。但是,应避免在同一软件包中混用 JUnit 3 和 JUnit 4 测试代码,因为这样可能会导致意外结果。如果要创建一个 JUnit 4 插桩测试类以在设备或模拟器上运行,则测试类必须以 @RunWith(AndroidJUnit4.class) 注释作为前缀。
以下代码段展示了如何编写 JUnit 4 插桩测试以验证 ChangeTextBehavior 类中的 changeText 操作是否正常工作:
Kotlin
@RunWith(AndroidJUnit4::class)
@LargeTest
class ChangeTextBehaviorTest {
val stringToBeTyped = "Espresso"
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
@Test fun changeText_sameActivity() {
// Type text and then press the button.
onView(withId(R.id.editTextUserInput))
.perform(typeText(stringToBeTyped), closeSoftKeyboard())
onView(withId(R.id.changeTextBt)).perform(click())
// Check that the text was changed.
onView(withId(R.id.textToBeChanged))
.check(matches(withText(stringToBeTyped)))
}
}Java
@RunWith(AndroidJUnit4.class)