Make Bazel maven dependencies not linked, but available in tests

378 Views Asked by At

I have a code, which depends on the maven package. I don't want this dependency to be packaged to a resulting JAR. In fact, I want to have only the source code in the resulting package, without all dependencies (the reason for it is that all dependencies will be already available in the class path).

In rules_jvm_external there is a neverlink option to mark the dependency as compile-only. So in my WORKSPACE file I have:

maven_install(
    artifacts = [
        maven.artifact("org.example.package", "my-dependency", "1.0.0", neverlink=True),
    ],
    ...
)

It works, but the problem is that tests use the same WORKSPACE file definitions and, as dependency is not available during the runtime, they're failing with java.lang.NoClassDefFoundError.

So I want to achieve both:

  • Make the dependency available in tests
  • Do not include the dependency in the JAR for deploy

How can I do this?

1

There are 1 best solutions below

0
On

rules_jvm_external allows to specify several maven_install declarations to handle multiple projects having different versions of the same artifact: link.

I'm not sure whether it's the right approach since I'm not having different versions – I have different metadata for the same package instead – but it works.

In my WORKSPACE file I did following:

maven_install(
    name = "maven_distribution",
    artifacts = [
        maven.artifact("org.example.package", "my-dependency", "1.0.0", neverlink=True),
    ],
    ...
)

maven_install(
    name = "maven_tests",
    artifacts = [
        maven.artifact("org.example.package", "my-dependency", "1.0.0", testonly=True),
    ],
    ...
)

In BUILD file for the java/ source:

java_library(
    name = "hooks",
    srcs = glob(["*.java"]),
    deps = [
        "@maven_distribution//:org_example_package_my_dependency"
    ],
)

And in BUILD file for the javatests/:

java_library(
    name = "tests",
    srcs = glob(["*.java"]),
    testonly = 1,
    deps = [
        "@maven_tests//:org_example_package_my_dependency"
    ],
)