Grouping JUnit Tests via Categories with Gradle

It is possible to specify packages of tests to run using Gradle by passing in a script parameter. For example:

gradle test --tests "com.some.package.*"

The downside is that each engineer would need to setup something on their machine whether that's a run configuration in IntelliJ or a shell script, etc. I wanted something that was baked into Gradle so it would just be a task.

I found this article on how to use JUnit's Categories but I needed to translate the maven config into gradle. Turns out, it is incredibly easy. I've defined 2 new tasks in my build.gradle file:

task testUnit(type: Test) {  
    useJUnit {
        includeCategories 'com.foo.UnitTest'
        excludeCategories 'com.foo.IntegrationTest'
    }
}

task testIntegration(type: Test) {  
    useJUnit {
        includeCategories 'com.foo.IntegrationTest'
        excludeCategories 'com.foo.UnitTest'
    }
}

And assuming the appropriate tests are tagged with the @Category annotation as described in the DZone article, running these new tasks will only run the included categories.