1、使用Robolectric
(1)在app\build.gradle里面配置
testImplementation "org.robolectric:robolectric:3.8"
testImplementation 'org.robolectric:shadows-support-v4:3.4-rc2'
testImplementation 'org.robolectric:shadows-multidex:3.0'
(2)在"...\xxxProject\build.gradle"中添加
repositories{
...
maven { url 'https://maven.google.com' } // Robolectric下载所需
}
2、使用数据库ObjectBox
(1)在app\build.gradle里面配置
apply plugin: 'io.objectbox'
implementation "io.objectbox:objectbox-android:${OBJECTBOX_VERSION}"
implementation "io.objectbox:objectbox-linux:${OBJECTBOX_VERSION}"
implementation "io.objectbox:objectbox-macos:$OBJECTBOX_VERSION"
implementation "io.objectbox:objectbox-windows:${OBJECTBOX_VERSION}"
annotationProcessor "io.objectbox:objectbox-processor:${OBJECTBOX_VERSION}"
前面四种根据运行环境去选择,依次是Android、linux系统、Macos系统和windows系统。比如我现在是要用Robolectric进行测试,运行环境是Windows,那么就只要配置
implementation "io.objectbox:objectbox-windows:${OBJECTBOX_VERSION}"
annotationProcessor "io.objectbox:objectbox-processor:${OBJECTBOX_VERSION}"
(2)在"...\xxxProject\build.gradle"中添加
dependencies {
...
classpath "io.objectbox:objectbox-gradle-plugin:${OBJECTBOX_VERSION}"
}
repositories{
...
maven { url "http://objectbox.net/beta-repo/" }
}
3、如果还需要使用到junit、Mocktio、PowerMocktio就需要增加下面的配置
// junit
testImplementation 'junit:junit:4.12'
// Mockito
testImplementation 'org.mockito:mockito-core:1.9.5'
// PowerMock
testCompile "org.powermock:powermock-module-junit4:1.7.3"
testCompile "org.powermock:powermock-module-junit4-rule:1.7.3"
testCompile "org.powermock:powermock-api-mockito2:1.7.3" //注意这里是mockito2
testCompile "org.powermock:powermock-classloading-xstream:1.7.3"
4、如果需要使用到jacoco覆盖率工具
(1)在app\build.gradle中添加配置:
apply from: "$rootDir/jacoco.gradle"
(2)把jacoco.gradle文件放在"...\xxxProject"下。
(3)在"...\xxxProject\app\libs"路径下添加org.jacoco.agent-0.8.2.jar包。
附上jacoco.gradle文件内容如下:
apply plugin: 'jacoco'
jacoco {
// https://bintray.com/bintray/jcenter/org.jacoco:org.jacoco.core
toolVersion = "0.8.2"
}
android {
testOptions {
unitTests.all {
jacoco {
includeNoLocationClasses = true
}
}
}
}
project.afterEvaluate {
android.applicationVariants.all { variant ->
def name = variant.name
def testTaskName = "test${name.capitalize()}UnitTest"
tasks.create(name: "${testTaskName}Coverage", type: JacocoReport, dependsOn: "$testTaskName") {
group = "Reporting"
description = "Generate Jacoco coverage reports for the ${name.capitalize()} build."
classDirectories = fileTree(
dir: "${project.buildDir}/intermediates/classes/${name}",
excludes: ['**/R.class',
'**/R$*.class',
'**/*$ViewInjector*.*',
'**/*$ViewBinder*.*',
'**/BuildConfig.*',
'**/Manifest*.*']
)
sourceDirectories = files(['src/main/java'].plus(android.sourceSets[name].java.srcDirs))
executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec")
reports {
xml.enabled = true
html.enabled = true
}
}
}
}
来源:CSDN
作者:shan286
链接:https://blog.csdn.net/shan286/article/details/103591632