How to run all JUnit tests with Bazel

Viewed 6566

I have been trying to run all JUnit tests in a directory with Bazel. As far as I know, the java_test rule is only capable of running a specific class. However, I'm looking for behavior more like mvn test which runs all JUnit tests in the project. How can I accomplish this?

1 Answers

The typical way to organize this is to have a java_test rule per Java test class, or per group of related Java test classes. Then java_tests can be grouped together using test_suite, if that's something you want to do.

You can run all tests in a package with:

bazel test //some/package:all

or in a package and its subpackages:

bazel test //some/package/...

or in the entire workspace:

bazel test //...

More about target patterns: https://docs.bazel.build/versions/master/guide.html#target-patterns

If you just want a java_test that runs all the tests in a directory, you can do something like

java_test(
    name = "tests",
    srcs = glob(["*Test.java"]),
    deps = [ ..... ],
)

but that may or may not be the right thing to do. In particular, if you want to just run one test or one test method (e.g. using --test_filter), bazel will still build all the java_test's dependencies. Also, note that globs only glob within a build package, and won't cross over into other packages.

Related