The Gerrit project contains a Starlark function called junit_tests. It takes a list of srcs and generates an AllTestsTestSuite.java file that runs tests in each Java class. It also generates a java_test target that includes the generated java file and all of the specified sources, deps, etc. Here is how to set it up.
First add these lines to your WORKSPACE file:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
# Re-usable building blocks for Bazel build tool
# https://gerrit.googlesource.com/bazlets/
# https://gerrit.googlesource.com/bazlets/+/968b97fa03a9d2afd760f2e8ede3d5643da390d2
git_repository(
name = "com_googlesource_gerrit_bazlets",
remote = "https://gerrit.googlesource.com/bazlets",
commit = "968b97fa03a9d2afd760f2e8ede3d5643da390d2",
)
# We cannot use the tar.gz provided over HTTP because it contains timestamps and each download has a
# different hash.
#http_archive(
# name = "com_googlesource_gerrit_bazlets",
# sha256 = "...",
# urls = [
# "https://gerrit.googlesource.com/bazlets/+archive/968b97fa03a9d2afd760f2e8ede3d5643da390d2.tar.gz",
# ],
#)
# This provides these useful imports:
# load("@com_googlesource_gerrit_bazlets//tools:maven_jar.bzl", "maven_jar")
# load("@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests")
Now add this to your BUILD file:
load("@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests")
junit_tests(
name = "AllTests",
srcs = glob(["*.java"]),
deps = [
"//java/com/company/a_package",
"@maven//:junit_junit",
"@maven//:org_hamcrest_hamcrest",
],
)
If your BUILD file is at $WORKSPACE_ROOT/javatests/com/company/a_package/BUILD then you can run these specific tests with:
bazel test //javatests/com/company/a_package:AllTests
You can run all of your java tests like this:
bazel test //javatests/...
If your directory contains a .java file that has no tests, the AllTests target will fail with "No runnable methods". The workaround is to add an empty test to the file:
/** Workaround for https://github.com/bazelbuild/bazel/issues/2539 */
@Test
public void emptyTest() {}
This is working for me with Bazel 2.0.0 on MacOS. I can also run the tests inside IntelliJ 2019.2 with the Bazel plugin.