无应用源码场景下如何用Kotlin通过Espresso启动Activity
无源码场景下Espresso启动Activity的核心逻辑
现有教程绑定被测应用源码,本质是为了直接引用目标Activity的Class对象省去类名采集步骤,无源码场景下完全可以绕开类引用,通过显式组件定位的方式完成Activity启动,逻辑和从Appium迁移过程中熟悉的appPackage、appActivity配置思路完全一致,不需要额外依赖被测应用的任何代码。
前置准备只需要两个从外部可获取的信息:
- 被测应用的包名
- 目标启动Activity的全限定类名
注意:这两个信息完全可以通过adb命令、应用安装包解析工具获取,不需要接触被测应用的源码
Kotlin实现的具体可运行代码
- 第一步先配置测试模块的基础依赖,在测试模块的build.gradle中引入核心依赖即可,不需要添加任何被测应用的源码依赖:
dependencies { androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") androidTestImplementation("androidx.test:runner:1.5.2") } android { defaultConfig { testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } }
- 第二步编写测试用例,通过Instrumentation原生API构造显式Intent,完全绕开对目标Activity类引用的依赖:
import android.app.Instrumentation import android.content.ComponentName import android.content.Intent import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import org.junit.Before import org.junit.Test import org.junit.runner.RunWith // 提前采集的目标应用信息,无源码场景下直接硬编码即可 const val TARGET_APP_PACKAGE = "com.your.targetapp" const val TARGET_ACTIVITY_FULL_PATH = "com.your.targetapp.entry.SplashActivity" @RunWith(AndroidJUnit4::class) @LargeTest class NoSourceAppLaunchTest { private lateinit var instrumentation: Instrumentation @Before fun setup() { instrumentation = InstrumentationRegistry.getInstrumentation() } @Test fun launchTargetActivityWithoutSourceCode() { // 构造靠组件名定位的显式Intent,不需要导入目标应用的任何类 val launchIntent = Intent().apply { component = ComponentName(TARGET_APP_PACKAGE, TARGET_ACTIVITY_FULL_PATH) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } // 直接通过Instrumentation启动目标Activity,完全不需要类引用 instrumentation.startActivitySync(launchIntent) // 等待应用同步加载完成 instrumentation.waitForIdleSync() // 后续Espresso交互、断言逻辑和有源码场景完全一致 onView(withId(android.R.id.content)).check(matches(isDisplayed())) } }
无源码场景的常见适配注意事项
- 快速获取准确Activity类名的方法:将被测应用安装到测试设备,打开需要启动的目标页面,执行
adb shell dumpsys window | grep mCurrentFocus,输出中冒号后的字符串就是目标Activity的全限定名,比静态解析安装包的结果更准确 - 非导出Activity的启动适配:如果目标Activity没有设置
android:exported="true",只需要将测试APK和被测APK使用同一签名文件签名,即可通过Instrumentation权限直接启动,不需要修改被测应用的任何配置 - 常用API的避坑提示:不要使用
ActivityScenario、ActivityTestRule这类强制要求传入Activity Class对象的规则组件,无源码场景下无法获取该引用;直接通过Instrumentation的startActivitySync方法配合自定义Intent启动即可 - 测试体验的一致性:Activity启动完成后,所有Espresso的视图匹配、交互操作、断言逻辑都和有源码的场景没有区别,不需要因为无源码修改测试操作的编写逻辑
内容的提问来源于stack exchange,提问作者Mohamed Wasiq
相关产品推荐
相关产品推荐

