在Android gradle项目中使用junit Category对robolectric测试进行分组

时间:2016-04-30 06:01:30

标签: android gradle junit robolectric

我想使用Junit类别注释对robolectric单元测试进行分组,以便某些测试不会在某种情况下运行。

在普通的java项目中,我知道我可以使用

apply plugin: 'java'
test {
    useJUnit {
        includeCategories 'FastTest'
    }
}

指定类别。

但显然'java'插件与Android插件'com.android.application'不兼容。

Error:The 'java' plugin has been applied, but it is not compatible with the Android plugins.

我尝试创建自定义gradle任务

sourceSets {
    test {
        java.srcDir file('src/test/java')
        resources.srcDir file('src/test/resources')
    }
}

task testWithFastCategory(type: Test) {
    group = "test"
    testClassesDir = sourceSets.test.output.classesDir
    classpath = sourceSets.test.runtimeClasspath
    useJUnit {
        includeCategories 'FastTest'
    }
}

但gradle似乎无法找到测试的正确类路径。

有人提供样本gradle设置,以便在Android项目下按类别运行robolectric测试吗?

1 个答案:

答案 0 :(得分:0)

忘记发布我的解决方案:

android {
  testOptions {
    unitTests.all {
        useJUnit {
            // Include or exclude unit tests with specific categories
            // ex. use -DincludeCategories=com.ooxx.test.FastRun
            // to run tests with 'FastRun' category on CI server.
            String defaultPackage = "com.ooxx.test."
            if (System.properties['includeCategories'] != null) {
                def categories = System.properties['includeCategories'].split(',')
                categories = categories.collect {
                    it.charAt(0).isUpperCase() ? defaultPackage + it : it
                }
                println name + ": include category"
                categories.each { category ->
                    println " - " + category
                }
                includeCategories categories as String[]
            }
            // ex. use -DexcludeCategories=com.ooxx.test.DoNotRun
            if (System.properties['excludeCategories'] != null) {
                def categories = System.properties['excludeCategories'].split(',')
                categories = categories.collect {
                    it.charAt(0).isUpperCase() ? defaultPackage + it : it
                }
                println name + ": exclude category"
                categories.each { category ->
                    println " - " + category
                }
                excludeCategories categories as String[]
            }
        }
      }
   }
}