Dylan Powers
Dylan Powers

Reputation: 249

How to run all JUnit tests with Bazel

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?

Upvotes: 7

Views: 11796

Answers (2)

ahumesky
ahumesky

Reputation: 5006

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 = [ "//some_pkg:some_dep" ],
)

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.

Upvotes: 17

Hashken
Hashken

Reputation: 4656

This is an old question, but hoping this answer would help others coming across this.

There is now java_test_suite rule available in contrib-rules-jvm repo. This has convenient features like:

  • Running all tests mentioned in sources
  • Automatically constructs a lib of shared code in the tests folder
  • Support for both JUnit4 and JUnit5

Upvotes: 1

Related Questions