Is there a way to restrict a test run to a particular JUnit category on the command line

So if you have a JUnit category called CoolTests, then you can write a test task to run those specifically like this:

task coolTests(type: Test) {
    useJUnit {
        includeCategories 'org.example.CoolTests'
    }
}

Which is nice.

However, it’s quite rare that i want to permanently bake a task for a specific category into my build script. Usually, i want to run tests in a category that corresponds to the work i happen to be doing at that moment, which changes frequently. To use the includeCategories mechanism, i have to make edits to my build script, and then remember to not check them in.

It would be great if there was a way to apply this filtering on the command line when running Gradle, rather than in the build script, similar to how --tests lets me filter by class name. Is there a way to do this? If not, can i suggest this feature be added?

There isn’t any built-in support for this, but as with any bit of configuration, you can read a system or project property and configure ‘includeCategories’ accordingly.

Well, it’s something. I ended up adding:

if (project.hasProperty("integrationTestCategory")) {
        useJUnit {
            includeCategories project.integrationTestCategory
        }
    }

Thanks for the suggestion.

It would be great if, some time in the future, there was direct support for this via the --tests flag or something similar.

1 Like