【Android Gradle 插件】TestOptions 配置 ④ ( org.gradle.api.tasks.testing.Test 单元测试配置类 | Android 单元测试示例 )

Android Plugin DSL Reference 参考文档 :





一、org.gradle.api.tasks.testing.Test 单元测试配置类



UnitTestOptions ( build.gradle#android#testOptions#unitTests ) 文档位置 : android-gradle-dsl/2.3/com.android.build.gradle.internal.dsl.TestOptions.UnitTestOptions.html

org.gradle.api.tasks.testing.Test 单元测试配置类 : https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/Test.html


1、Test 单元测试配置回顾


在上一篇博客 【Android Gradle 插件】TestOptions 配置 ③ ( TestOptions#unitTests 脚本块配置 | UnitTestOptions 配置简介 ) 中 , 参考文档 https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/Test.html , 有如下单元测试配置示例 ;

Gradle 中 Test 单元测试配置类参考 :

 plugins {
    
    
     id 'java' // adds 'test' task
 }

 test {
    
    
   // Discover and execute JUnit4-based tests
   useJUnit()

   // Discover and execute TestNG-based tests
   useTestNG()

   // Discover and execute JUnit Platform-based tests
   useJUnitPlatform()

   // set a system property for the test JVM(s)
   systemProperty 'some.prop', 'value'

   // explicitly include or exclude tests
   include 'org/foo/**'
   exclude 'org/boo/**'

   // show standard out and standard error of the test JVM(s) on the console
   testLogging.showStandardStreams = true

   // set heap size for the test JVM(s)
   minHeapSize = "128m"
   maxHeapSize = "512m"

   // set JVM arguments for the test JVM(s)
   jvmArgs '-XX:MaxPermSize=256m'

   // listen to events in the test execution lifecycle
   beforeTest { descriptor ->
      logger.lifecycle("Running test: " + descriptor)
   }

   // Fail the 'test' task on the first test failure
   failFast = true

   // listen to standard out and standard error of the test JVM(s)
   onOutput { descriptor, event ->
      logger.lifecycle("Test: " + descriptor + " produced standard out/err: " + event.message )
   }
 }

2、启动单元测试


启用 TestNG 支持 , 也就是启用 单元测试 , 默认的单元测试类型是 JUnit 单元测试 ;

useTestNG()

3、设置 JVM 系统属性


为测试的 Java 虚拟机 ( JVM ) 设置系统属性 , Gradle 中的单元测试 运行在独立的 JVM 虚拟机中 ,

   // set a system property for the test JVM(s)
   systemProperty 'some.prop', 'value'

上述设置了 JVM 系统属性值 , 可以通过

System.getProperty("some.prop") 

代码 , 在 单元测试 类中 , 获取该 ‘some.prop’ 对应的 ‘value’ 值 ;


4、打开命令行标准输出


如果想要在 Console 命令行中查看测试过程 , 需要开启 Java 虚拟机的 标准输出 和 标准错误 ;

   // show standard out and standard error of the test JVM(s) on the console
   testLogging.showStandardStreams = true




二、单元测试示例



单元测试类

单元测试类如下 :

package kim.hsl.svg

import org.junit.Test

import org.junit.Assert.*

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    
    
    @Test
    fun addition_isCorrect() {
    
    
        assertEquals(4, 2 + 2)
        System.out.println(System.getProperty("some.prop"))
    }
}

gradle 配置

build.gradle 配置如下 :

plugins {
    
    
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    
    

    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
    
    
        applicationId "kim.hsl.svg"
        minSdkVersion 18
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        // 生成 PNG 图片配置
        //generatedDensities = ['hdpi', 'mdpi', 'xhdpi',  'xxhdpi', 'xxxhdpi']

        // 使用 com.android.support:appcompat 支持库配置
        vectorDrawables.useSupportLibrary = true

        // 国际化资源配置, 只打包默认资源与英文资源
        resConfigs 'en'

        ndk {
    
    
            abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
        }

        buildConfigField("boolean", "isGooglePlay", "true")
        buildConfigField("String", "market", '"GooglePlay"')

        //applicationIdSuffix ".tom"
    }

    signingConfigs {
    
    
        mySigningConfig {
    
    
            storeFile file("debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
    }

    buildTypes {
    
    
        release {
    
    
            // 是否开启优化混淆
            minifyEnabled true
            // 是否启用资源压缩 , 未使用的资源会被优化
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
    
    
            multiDexEnabled true
            multiDexKeepFile file('keep_in_main.txt')
        }
    }

    // 配置资源编译工具 aapt
    aaptOptions {
    
    
        // aapt 附加参数
        //additionalParameters '-S', 'src/main/res2', '--auto-add-overlay'
    }

    lintOptions {
    
    
        // 编译时遇到错误, 停止编译
        abortOnError false
    }

    sourceSets {
    
    
        main {
    
    
            res.srcDirs 'src/main/res', 'src/main/res2'
        }
    }

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

    buildFeatures {
    
    
        dataBinding = true
    }

    testOptions {
    
    
        animationsDisabled true
        unitTests.all {
    
    
            // 设置 JVM 系统属性
            systemProperty 'some.prop', 'value'
            // 开启标准化化输出
            testLogging.showStandardStreams = true
        }
    }
}

dependencies {
    
    

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'

    // 矢量图支持库 , 支持 5.0 以下版本手机使用矢量图 , 这个是创建应用时自带的配置
    implementation 'androidx.appcompat:appcompat:1.2.0'

    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

1、右键运行单元测试


在单元测试类中 , 鼠标右键点击单元测试方法名 , 即可执行该方法 ;

在这里插入图片描述

注意 : 在单元测试类中 , 点击右键运行不会生成测试报告 ,

执行结果 :
在这里插入图片描述


3、执行单元测试 Gradle 任务


标准的单元测试 , 需要在 Terminal 中执行

gradlew :app:testDebugUnitTest

命令 , 执行单元测试 , 并在命令行输出结果 , 最终生成测试报告 ;

在这里插入图片描述

执行上述命令 , 即可开始进行单元测试 ;

在这里插入图片描述


4、查看单元测试命令行输出


执行时会在 Terminal 终端中打印出 systemProperty 'some.prop', 'value' 配置的 JVM 系统属性 ;

Y:\002_WorkSpace\001_AS\SVG>gradlew :app:testDebugUnitTest

> Task :app:testDebugUnitTest

kim.hsl.svg.ExampleUnitTest > addition_isCorrect STANDARD_OUT
    value

BUILD SUCCESSFUL in 9s
21 actionable tasks: 2 executed, 19 up-to-date
Y:\002_WorkSpace\001_AS\SVG>

在这里插入图片描述


5、查看单元测试报告


单元测试报告生成路径 : app/build/reports/androidTests/connected/flavors/debugAndroidTest/kim.hsl.svg.ExampleInstrumentedTest.html

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/han1202012/article/details/124919531