Android 测试全景:从单元测试到 UI 自动化的完整实践
Android 测试全景:从单元测试到 UI 自动化的完整实践
在 Android 开发中,测试不是可选项,而是保证代码质量、减少线上事故的必备工程实践。本文将带你从零开始搭建一套完整的测试体系,涵盖单元测试、Android 特有测试场景以及 UI 自动化测试的全链路实践。
单元测试基础:JUnit、Mockito 与 Truth
单元测试的核心是隔离验证——针对单个类或方法,屏蔽外部依赖,快速验证逻辑正确性。
JUnit 5 快速上手
JUnit 是 Java 生态的测试基石。在 build.gradle 中引入依赖:
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' }
tasks.withType(Test) { useJUnitPlatform() }
一个典型的单元测试示例:
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEachclass UserValidatorTest { private lateinit var validator: UserValidator
@BeforeEach fun setup() { validator = UserValidator() }
@Test fun
valid email should pass validation() { val result = validator.validateEmail("user@example.com") assertTrue(result.isValid) }
@Test funinvalid email should return error message() { val result = validator.validateEmail("not-an-email") assertFalse(result.isValid) assertEquals("Invalid email format", result.errorMessage) } }
Mockito:模拟外部依赖
当测试对象依赖数据库、网络或其他组件时,Mockito 可以创建轻量级替身:
testImplementation 'org.mockito:mockito-core:5.3.1'
testImplementation 'org.mockito.kotlin:mockito-kotlin:5.0.0'
实战示例——测试一个依赖网络 API 的 Repository:
import org.mockito.kotlin.* import kotlinx.coroutines.test.runTestclass UserRepositoryTest { private val api: UserApi = mock() private val repository = UserRepository(api)
@Test fun
fetchUser should return user when API succeeds() = runTest { // Given val userId = "123" val expectedUser = User(userId, "Alice", "alice@test.com") whenever(api.getUser(userId)).thenReturn(expectedUser)// When val result = repository.fetchUser(userId)
// Then assertEquals(expectedUser, result) verify(api, times(1)).getUser(userId) }
@Test fun
fetchUser should throw exception when API fails() = runTest { // Given whenever(api.getUser(any())).thenThrow(NetworkException("Connection timeout"))
// When & Then assertThrows<NetworkException> { repository.fetchUser("123") } } }
Truth:让断言更易读
Google 的 Truth 库提供流畅的断言 API:
testImplementation 'com.google.truth:truth:1.1.5'
对比传统 JUnit 断言:
import com.google.common.truth.Truth.assertThat
@Test funtruth makes assertions readable() { val numbers = listOf(1, 2, 3, 4, 5) // JUnit 风格 assertTrue(numbers.contains(3)) assertEquals(5, numbers.size) // Truth 风格(更自然) assertThat(numbers).contains(3) assertThat(numbers).hasSize(5) assertThat(numbers).containsExactly(1, 2, 3, 4, 5).inOrder() }
Android 单元测试:本地测试 vs 仪器测试
Android 的测试分为两类:本地测试(运行在 JVM)和仪器测试(运行在设备/模拟器)。
Robolectric:在 JVM 上模拟 Android 框架
Robolectric 让你无需启动模拟器即可测试 Android 组件:
testImplementation 'org.robolectric:robolectric:4.10.3'
测试一个带 Context 依赖的工具类:
import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import com.google.common.truth.Truth.assertThat@RunWith(RobolectricTestRunner::class) class SharedPrefsManagerTest { private val context = RuntimeEnvironment.getApplication() private val manager = SharedPrefsManager(context)
@Test fun
saveToken should persist token correctly() { manager.saveToken("abc123") val token = manager.getToken() assertThat(token).isEqualTo("abc123") }
@Test funclearToken should remove stored token() { manager.saveToken("xyz") manager.clearToken() assertThat(manager.getToken()).isNull() } }
本地测试 vs 仪器测试的选择
| 场景 | 推荐方式 | 原因 | |------|---------|------| | 纯业务逻辑(ViewModel、UseCase) | 本地测试 | 速度快,无需设备 | | 轻量 Android API(SharedPreferences、Intent) | Robolectric | 接近真实环境,仍在 JVM 运行 | | 复杂 UI 交互、动画、传感器 | 仪器测试 | 必须在真实环境验证 | | 数据库(Room)、文件 I/O | 两者皆可 | Robolectric 快,仪器测试更准确 |
UI 自动化测试:Espresso 与 UI Automator
Espresso:应用内 UI 测试
Espresso 是 Google 官方的 UI 测试框架,适合测试单个应用的界面交互:
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test:rules:1.5.0'
完整登录流程测试示例:
import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith@RunWith(AndroidJUnit4::class) class LoginActivityTest { @get:Rule val activityRule = ActivityScenarioRule(LoginActivity::class.java)
@Test fun loginWithValidCredentials_shouldNavigateToHome() { // 输入用户名和密码 onView(withId(R.id.edit_username)) .perform(typeText("testuser"), closeSoftKeyboard()) onView(withId(R.id.edit_password)) .perform(typeText("password123"), closeSoftKeyboard())
// 点击登录按钮 onView(withId(R.id.btn_login)) .perform(click())
// 验证跳转到主页 onView(withId(R.id.text_welcome)) .check(matches(isDisplayed())) .check(matches(withText("Welcome, testuser!"))) }
@Test fun loginWithEmptyFields_shouldShowError() { onView(withId(R.id.btn_login)) .perform(click())
onView(withId(R.id.text_error)) .check(matches(withText("Please enter username and password"))) } }
UI Automator:跨应用测试
当需要测试跨应用场景(如分享到系统应用、权限弹窗),使用 UI Automator:
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.3.0'
测试权限请求流程:
import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiSelector import androidx.test.uiautomator.Until@Test fun requestCameraPermission_shouldGrantAccess() { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
// 触发权限请求 onView(withId(R.id.btn_open_camera)).perform(click())
// 等待系统权限弹窗 device.wait(Until.hasObject(By.text("Allow")), 3000)
// 点击"允许"按钮 val allowButton = device.findObject(UiSelector().text("Allow")) if (allowButton.exists()) { allowButton.click() }
// 验证相机已打开 onView(withId(R.id.camera_preview)) .check(matches(isDisplayed())) }
测试覆盖率与持续集成
生成测试覆盖率报告
在 build.gradle 中启用 JaCoCo:
android { buildTypes { debug { testCoverageEnabled true } } }tasks.register('jacocoTestReport', JacocoReport) { dependsOn 'testDebugUnitTest', 'createDebugCoverageReport'
reports { xml.required = true html.required = true }
def fileFilter = [ '**/R.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*_Factory.*' ]
def kotlinTree = fileTree(dir: "$buildDir/tmp/kotlin-classes/debug", excludes: fileFilter) def javaTree = fileTree(dir: "$buildDir/intermediates/javac/debug", excludes: fileFilter)
classDirectories.setFrom(files([kotlinTree, javaTree])) sourceDirectories.setFrom(files(['src/main/java', 'src/main/kotlin'])) executionData.setFrom(fileTree(dir: buildDir, includes: [ 'jacoco/testDebugUnitTest.exec', 'outputs/code_coverage/debugAndroidTest/connected/**/*.ec' ])) }
运行命令生成报告:
./gradlew jacocoTestReport
报告输出在 build/reports/jacoco/jacocoTestReport/html/index.html。
在 CI 中集成测试
GitHub Actions 配置示例(.github/workflows/test.yml):
name: Android CIon: push: branches: [ main, develop ] pull_request: branches: [ main ]
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK 17 uses: actions/setup-java@v3 with: java-version: '17' distribution: 'temurin' - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Run unit tests run: ./gradlew testDebugUnitTest - name: Run instrumented tests uses: reactivecircus/android-emulator-runner@v2 with: api-level: 33 target: google_apis arch: x86_64 script: ./gradlew connectedDebugAndroidTest - name: Generate coverage report run: ./gradlew jacocoTestReport - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: files: ./app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml
实战案例:从零搭建测试体系
假设我们有一个新闻应用,从零搭建测试体系的步骤:
第一步:项目依赖配置
在 app/build.gradle 中统一配置测试依赖:
dependencies {
// 单元测试
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.3.1'
testImplementation 'org.mockito.kotlin:mockito-kotlin:5.0.0'
testImplementation 'com.google.truth:truth:1.1.5'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3'
testImplementation 'androidx.arch.core:core-testing:2.2.0'
testImplementation 'org.robolectric:robolectric:4.10.3'
// UI 测试
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test:rules:1.5.0'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.3.0'
}
第二步:ViewModel 单元测试
class NewsViewModelTest { @get:Rule val instantExecutorRule = InstantTaskExecutorRule() private val repository: NewsRepository = mock() private lateinit var viewModel: NewsViewModel@Before fun setup() { viewModel = NewsViewModel(repository) }
@Test fun
loadNews should update LiveData when repository returns data() = runTest { // Given val articles = listOf( Article("1", "Title 1", "Content 1"), Article("2", "Title 2", "Content 2") ) whenever(repository.fetchLatestNews()).thenReturn(Result.success(articles))// When viewModel.loadNews()
// Then assertThat(viewModel.newsLiveData.value).isEqualTo(articles) assertThat(viewModel.isLoadingLiveData.value).isFalse() } }
第三步:Repository 测试(含数据库和网络)
@RunWith(RobolectricTestRunner::class) class NewsRepositoryTest { private lateinit var database: NewsDatabase private val api: NewsApi = mock() private lateinit var repository: NewsRepository@Before fun setup() { val context = RuntimeEnvironment.getApplication() database = Room.inMemoryDatabaseBuilder(context, NewsDatabase::class.java) .allowMainThreadQueries() .build() repository = NewsRepository(api, database.newsDao()) }
@Test fun
fetchLatestNews should cache results in database() = runTest { // Given val remoteArticles = listOf(Article("1", "Remote Title", "Content")) whenever(api.getLatestNews()).thenReturn(remoteArticles)// When repository.fetchLatestNews()
// Then val cachedArticles = database.newsDao().getAllArticles() assertThat(cachedArticles).hasSize(1) assertThat(cachedArticles[0].title).isEqualTo("Remote Title") } }
第四步:完整 UI 流程测试
@RunWith(AndroidJUnit4::class) @LargeTest class NewsFlowTest { @get:Rule val activityRule = ActivityScenarioRule(MainActivity::class.java)@Test fun userCanBrowseAndReadArticle() { // 等待列表加载 onView(withId(R.id.recycler_news)) .check(matches(isDisplayed()))
// 点击第一篇文章 onView(withId(R.id.recycler_news)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click()))
// 验证详情页显示 onView(withId(R.id.text_article_title)) .check(matches(isDisplayed()))
// 点击分享按钮 onView(withId(R.id.btn_share)) .perform(click())
// 使用 UI Automator 验证系统分享面板 val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) val sharePanel = device.findObject(UiSelector().textContains("Share")) assertThat(sharePanel.exists()).isTrue() } }
测试金字塔与最佳实践
遵循测试金字塔原则:
- 70% 单元测试:快速、稳定、低成本 - 20% 集成测试:验证模块间协作 - 10% UI 测试:覆盖核心用户流程
关键建议:1. 测试要快:单元测试应在毫秒级完成,整个测试套件不超过 5 分钟 2. 测试要独立:每个测试可以独立运行,不依赖执行顺序 3. 测试要清晰:使用 Given-When-Then 结构,测试名称描述预期行为 4. Mock 要克制:只 mock 外部依赖,不要 mock 被测对象本身 5. 持续演进:新功能必须有测试,老代码逐步补测试
总结
测试不是负担,而是重构的信心来源和质量的最后防线。从单元测试的快速反馈,到 UI 自动化测试的端到端验证,完整的测试体系能让你在迭代时更从容、在上线时更放心。
现在就为你的项目配置第一个测试用例吧——从最核心的业务逻辑开始,逐步建立覆盖网,你会发现代码质量和开发体验都会有质的提升。

浙公网安备 33010602011771号