You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多Android Library模块共享自定义AndroidJUnitRunner?

复用Hilt自定义AndroidJUnitRunner的可行方案

这种复用方式完全可行,你之前测试失败的核心问题是自定义Runner的存放位置和依赖逻辑错误,调整后就能实现多模块共享同一个测试Runner。

问题根源

你把CustomTestRunner放在了:library:ui-testing:common模块的androidTest目录下,这个目录的代码属于模块私有测试代码,其他模块依赖时不会包含这部分内容,导致功能模块找不到Runner类,最终测试无法正常初始化,出现Starting 0 tests的错误。

实现步骤

1. 重构公共测试模块结构

修改:library:ui-testing:common模块,把CustomTestRunner从androidTest目录移到main目录下(作为模块的公共代码),并调整模块的build.gradle配置:

apply plugin: "com.android.library"
apply plugin: "kotlin-android"
apply plugin: "dagger.hilt.android.plugin"

android {
    compileSdk 34

    defaultConfig {
        minSdk 21
        targetSdk 34
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    // 必须依赖AndroidX Test Runner和Hilt核心库
    implementation "androidx.test:runner:1.5.2"
    implementation "com.google.dagger:hilt-android:2.48"
    kapt "com.google.dagger:hilt-android-compiler:2.48"
}

2. 编写共享的CustomTestRunner

在main/java/com/uitesting/common/路径下创建Runner类:

package com.uitesting.common

import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication

class CustomTestRunner : AndroidJUnitRunner() {
    override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }
}

3. 在统一配置文件中全局配置

修改android-library-config.gradle,添加对公共测试模块的依赖,并全局设置测试运行器:

apply plugin: "com.android.library"
apply plugin: "kotlin-android"
apply plugin: "dagger.hilt.android.plugin"

android {
    // 保留你原有的Android配置
    defaultConfig {
        // 全局指定共享的测试运行器
        testInstrumentationRunner "com.uitesting.common.CustomTestRunner"
    }
}

dependencies {
    // 让所有Library模块都依赖公共测试模块
    androidTestImplementation project(":library:ui-testing:common")
    
    // 统一添加Hilt测试依赖
    androidTestImplementation "com.google.dagger:hilt-android-testing:2.48"
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:2.48"
}

4. 功能模块无需额外配置

所有功能模块保持原有的apply from: "$rootProject.projectDir/android-library-config.gradle"即可,不需要再单独配置Runner或依赖。

验证效果

重新编译并运行任意功能模块的仪器化测试,此时测试运行器会正常加载CustomTestRunner,并初始化HiltTestApplication,测试就能正常执行。

内容的提问来源于stack exchange,提问作者Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:01:02