Android test全景:从单元 test到 UI 自动化的完整实践

简介: 本文系统讲解Android测试体系建设:涵盖JUnit/Truth单元测试、Mockito依赖隔离、Robolectric本地Android测试、Espresso UI测试及UI Automator跨应用测试,并集成JaCoCo覆盖率与GitHub Actions持续集成,助力打造高质量、可维护的Android应用。

在 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.BeforeEach

class 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
    fun `invalid 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.runTest

class 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
fun `truth 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
    fun `clearToken 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 CI

on:
  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 自动化测试的端到端验证,完整的测试体系能让你在迭代时更从容、在上线时更放心。

现在就为你的项目配置第一个测试用例吧——从最核心的业务逻辑开始,逐步建立覆盖网,你会发现代码质量和开发体验都会有质的提升。

相关文章
|
1月前
|
数据采集 人工智能 运维
AI 搜索引擎优化如何落地?从实体校准、内容建设到信源迭代全流程解析
AI搜索正重塑商业信息获取方式。本文提出GEO(生成式引擎优化)方法论,强调以“现状审计→实体标准化→词库蒸馏→结构化内容→可信源矩阵→监测迭代”闭环,助力企业事实信息被大模型检索、核验并引用,抢占AI答案席位。
244 1
|
1月前
|
缓存 人工智能 自然语言处理
阿里云qwen3.8-flash最全介绍:模型能力、适用场景、使用教程与最新活动参考
本文介绍了通义千问Qwen3.8-Flash这款兼顾性能与速度的多模态大模型,它拥有百万级上下文窗口,原生支持图文视频多模态输入,在长文档处理、编程辅助、高并发应用场景表现突出。文章覆盖五大地域部署差异、最新下调后的Token计费标准、两种接入方式与限流规则,叠加新用户免费额度、夜间4折等活动,是企业与开发者平衡效果与成本的高性价比选型。
|
1月前
|
人工智能 测试技术 定位技术
Skill粒度拆多细?一个测试总监踩过的坑和4条铁律
本文总结测试AI Agent技能(Skill)设计的四大铁律:一个Skill只做一件事、2-3模块为佳、SKILL.md≤500行、description+when_to_use≤1536字符。通过47→12个Skill的重构实践,揭示过度拆分反致AI选错、上下文爆炸、维护困难等痛点,强调“精”胜于“多”。
|
1月前
|
人工智能 数据挖掘 BI
千问办公QwenWork深度解析:基于Qwen3.8,六大核心能力重构企业全自动化工作流与计费选型指南
AI办公应用快速普及的今天,大量工具依旧停留在对话问答层面,只能输出文本草稿,很难直接产出可以投入业务使用的最终产物。企业日常办公当中,员工需要在多款软件之间来回切换,沟通协作、文档撰写、数据分析、网页制作分别对应不同平台,复制粘贴操作占用大量工作时间。即便借助普通大模型生成内容,也经常遇到格式错乱、表格缺少计算公式、生成网页还需要额外部署上线等各类问题,AI产出物需要大量二次加工才可以使用。除此之外,企业内部数据相互割裂,AI无法直接读取群聊记录、会议纪要、审批单据、内部知识库,业务需求需要人工重新复述;面对法务审核、电商数据分析、代码开发这类垂直任务,使用者需要编写复杂冗长提示词才能够得到
656 2
|
3月前
|
人工智能 运维 监控
|
3月前
|
存储 人工智能 运维
让 Agent 越用越准、成本越来越低:AgentLoop 的 Agent 经验自进化闭环
企业 Agent 上线后,如何在不重新训练模型的情况下提升准确率、稳定性并优化单位成功成本?本文介绍 AgentLoop 如何基于真实运行轨迹自动生成可复用经验,通过 Skill 和 CLI 按需召回,并给出控制台接入步骤及与 Memory、RAG、微调、RL 的差异。
625 1
|
2月前
|
人工智能 运维 自然语言处理
强制国标18个月倒计时:企业AI安全的六大关口怎么过
6月27日,国标委发布《智能体应用安全基本要求》强制性国标(2026年41号),设六道安全关:资产盘点、身份权限、数据管控、多模态防护、全链路审计、应急熔断。本文不复述条文,而是逐关解析落地难点与工程解法——从流量侧自动盘点AI资产,到Agent身份映射、PII实时拦截、多模态越狱防御、结构化审计溯源,再到凭证级秒级熔断,助力企业高效合规。
351 0
|
2月前
|
人工智能 自然语言处理 测试技术
不用写一行代码的测试时代来了:2026年AI测试智能体搭建全指南
本文探讨2026年AI测试智能体带来的范式革命:从“写脚本”迈向“说人话”。无需编码,仅凭自然语言指令即可完成端到端测试;AI自动理解意图、定位元素、执行操作并智能断言。涵盖Harness、Autonoma、qpilot等主流方案对比与实操指南,并揭示落地避坑要点与人机协同新趋势。
|
存储 缓存 NoSQL
跟着源码学IM(十一):一套基于Netty的分布式高可用IM详细设计与实现(有源码)
本文将要分享的是如何从零实现一套基于Netty框架的分布式高可用IM系统,它将支持长连接网关管理、单聊、群聊、聊天记录查询、离线消息存储、消息推送、心跳、分布式唯一ID、红包、消息同步等功能,并且还支持集群部署。
14189 1
|
6月前
|
人工智能 监控 Kubernetes
LoongCollector + ACS Agent Sandbox:构建 AI Agent 生产级运行平台
文章介绍了阿里云ACSAgentSandbox与LoongCollector协同构建的AIAgent生产级运行平台,通过沙箱隔离保障运行时安全,并以高性能、全链路可观测能力解决Agent行为不可预测和执行风险难题。
3293 96