How to run all JUnit tests with Bazel
Asked Answered
O

2

7

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?

Orleans answered 1/4, 2020 at 20:55 Comment(0)
C
16

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.

Coseismal answered 1/4, 2020 at 21:34 Comment(4)
If I try to run all tests in a directory using glob, I get cannot determine test class. However, I really just want it to run all tests annotated with @Test in the current package. Any advice?Orleans
you'll need a junit test suite (specified in the test_class attribute) that discovers the test classes. have a look at the solutions here: stackoverflow.com/questions/46365464Coseismal
Note for Bazel noobies like me: those ... are not a "fill in the blank", its literally the command to run all the testsChestnut
i replaced deps = [ ..... ] with deps = [ "//some_pkg:some_dep" ] to hopefully make that less confusingCoseismal
Z
0

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
Zipnick answered 23/3 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.