安卓单元测试--在真机上跑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

  1. 在app/src下新建androidTest文件夹(androidTest文件下的case会在真机上运行,test文件下的case在开发主机Java虚拟机上运行)
  2. 创建测试类

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","************");
    }
}

四、 运行效果

image.png
image.png

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

import android.content.Context;
import android.support.test.InstrumentationRegistry;


public void testProjectInit() throws IOException{

        Context context = InstrumentationRegistry.getTargetContext();
        Log.i("example test",context.getPackageName());
 }

六、参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容