Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping robolectric tests using junit Category in an Android gradle project

I want to use Junit Category annotation to group the robolectric unit tests so that some tests will not run in a certain situation.

In a normal java project, I know I can use

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

to specify the category.

but apparently the 'java' plugin is not compatible with the Android plugins 'com.android.application'.

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

I tried to create a custom gradle task

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'
    }
}

but gradle seems not able to locate the right classpath for the test.

Could someone provider a sample gradle setting to run robolectric tests grouping by Category under an Android project?

like image 582
tch0106 Avatar asked Apr 30 '16 06:04

tch0106


1 Answers

Forgot to post my solution:

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[]
            }
        }
      }
   }
}
like image 135
tch0106 Avatar answered Nov 24 '22 10:11

tch0106