安卓单元测试--在真机上跑AndroidJUnitRunner

一、AndroidJUnitRunner 简介

AndroidJUnitRunner 类是一个 JUnit 测试运行程序,可让您在 Android 设备上运行 JUnit 3 或 JUnit 4 型测试类,包括使用 Espresso 和 UI Automator 测试框架的测试类。

此测试运行程序负责将测试软件包和被测应用加载到设备上、运行测试并报告测试结果。此类取代了仅支持 JUnit 3 测试的 InstrumentationTestRunner 类

二、 环境准备

  • 在app/build.gradle中添加依赖:
  •  dependencies {
        testImplementation  'junit:junit:4.12'
        androidTestImplementation  'androidx.test:runner:1.1.1'
        androidTestImplementation  'androidx.test.espresso:espresso-core:3.1.1'
      defaultConfig {
           testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
           // The following argument makes the Android Test Orchestrator run its
           // "pm clear" command after each test invocation. This command ensures
           // that the app's state is completely cleared between tests.
           testInstrumentationRunnerArguments clearPackageData: 'true'
          testOptions {
            execution 'ANDROIDX_TEST_ORCHESTRATOR'
    

    三、 新建example case

  • 在app/src下新建androidTest文件夹(androidTest文件下的case会在真机上运行,test文件下的case在开发主机Java虚拟机上运行)
  • 创建测试类
  • import org.junit.Test; import java.io.IOException; public class ExamplleTest { @Test public void setDataSource() { //打印手机型号 Log.i("example test","************"); Log.i("example test",android.os.Build.MODEL); Log.i("example test",android.os.Build.VERSION.RELEASE); Log.i("example test","************");

    四、 运行效果

    五、 获取被测试项目的上下文

    import android.content.Context;
    import android.support.test.InstrumentationRegistry;
    public void testProjectInit() throws IOException{
            Context context = InstrumentationRegistry.getTargetContext();
            Log.i("example test",context.getPackageName());