Android单元测试

2019-09-28  本文已影响0人  DON_1007

由于项目结构特殊性,不适合使用仪器化测试,这里选用robolectric

一、robolectric集成

android {
    // Robolectric
    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }
    testOptions.unitTests.all {
        testLogging {
            events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
            outputs.upToDateWhen { false }
            showStandardStreams = true
        }
    }
}

dependencies {
    ...
    // 单元测试
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.robolectric:robolectric:4.3'
}

src目录下创建于main同级目录testtest创建于代码相同结构测试代码,如原代码com.hpplay.sdk.sink.adapter.Feature.java,这在test目录新建类com.hpplay.sdk.sink.adapter.FeatureTest.java,实现测试代码

package com.hpplay.sdk.sink.adapter;

import android.content.Context;

import com.hpplay.sdk.sink.util.Utils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

/**
 * Created by don on 2019-09-05
 */
@RunWith(RobolectricTestRunner.class)
public class FeatureTest {

    @Test
    public void getVolumeType() {
        System.out.println(Feature.getVolumeType(Utils.getApplication()));
    }

}

二、执行单元测试

选中FeatureTest右键选择执行单元测试

image.png

三、命令行执行单元测试

所有渠道和编译类型 gradlew :sdk-bu:test
指定渠道和编译类型 gradlew :sdk-bu:testHappytestDebugUnitTest

image.png

四、生成测试报告并导出

生成测试报告需要借助jacoco
gradle中配置jacoco

apply plugin: 'jacoco'

...

jacoco {
    toolVersion = "0.8.4"
}

def coverageSourceDirs = [
        '../sdk-bu/src/main/java'
]

task jacocoReport(type:JacocoReport, dependsOn: ":sdk-bu:testHappytestDebugUnitTest") {
    group = "Reporting"

    description = "Generate Jacoco coverage reports"

    classDirectories = fileTree(
            dir: '../sdk/build/intermediates/classes/happytest/debug',
            excludes: ['**/R.class',
                       '**/R$*.class',
                       '**/*$ViewInjector*.*',
                       '**/BuildConfig.*',
                       '**/Manifest*.*']
    )

    additionalSourceDirs = files(coverageSourceDirs)
    sourceDirectories = files(coverageSourceDirs)
    executionData = files('../sdk-bu/build/jacoco/testHappytestDebugUnitTest.exec')

    reports {
        xml.enabled = true
        html.enabled = true
    }

}

执行命令 gradlew :sdk-bu:jacocoReport
build/reports/tests/testHappytestDebugUnitTest中会生成测试报告,
在浏览器中打开index.html,可以查看测试报告

image.png

参考:

https://www.jianshu.com/p/aa51a3e007e2
https://blog.csdn.net/yugong2009/article/details/80462094

上一篇下一篇

猜你喜欢

热点阅读