安卓單元測試--在真機上跑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());
 }

六、參考文章

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容