如何通过Bazel从JUnit测试执行中找到指向Java源代码文件的路径

2022-08-21 00:00:00 bazel java bazel-java

我想通过JUnit测试检查我们的monorepo代码库中的一个文本文件。JUnit测试通过bazel test命令执行。如何将Bazel配置为将源代码目录路径(而不是缓存的编译JAR文件路径)传递给单元测试?它可以是CLI参数、环境变量等。


解决方案

要做到这一点,一种方法是使用data属性,该属性使文件在运行时可用于测试(和其他二进制文件),而对于Java,Bazel提供了用于查找数据文件的运行文件库。例如:

BUILD

java_test(
  name = "TextFileTest",
  srcs = ["javatests/txtfile/TextFileTest.java"],
  data = ["text.txt"],
  deps = [
      "@bazel_tools//tools/java/runfiles:runfiles",
      "@maven//:junit_junit",
  ],
)

WORKSPACE

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

RULES_JVM_EXTERNAL_TAG = "4.2"
RULES_JVM_EXTERNAL_SHA = "cd1a77b7b02e8e008439ca76fd34f5b07aecb8c752961f9640dea15e9e5ba1ca"

http_archive(
    name = "rules_jvm_external",
    strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
    sha256 = RULES_JVM_EXTERNAL_SHA,
    url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
)

load("@rules_jvm_external//:defs.bzl", "maven_install")

maven_install(
    artifacts = [
        "junit:junit:4.13.2",
    ],
    repositories = [
        "https://repo1.maven.org/maven2",
    ],
)

javatests/txtfile/TextFileTest.java

package txtfile;

import com.google.devtools.build.runfiles.Runfiles;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TextFileTest {

  @Test
  public void testTextFile() throws Exception {
    Runfiles runfiles = Runfiles.create();
    Path path = Paths.get(runfiles.rlocation("__main__/text.txt"));
    String line = Files.readAllLines(path).get(0);
    Assert.assertEquals(line, "this is text");
  }
}

text.txt

this is text
$ bazel test TextFileTest
INFO: Build option --test_sharding_strategy has changed, discarding analysis cache.
INFO: Analyzed target //:TextFileTest (0 packages loaded, 547 targets configured).
INFO: Found 1 test target...
Target //:TextFileTest up-to-date:
  bazel-bin/TextFileTest.jar
  bazel-bin/TextFileTest
INFO: Elapsed time: 0.288s, Critical Path: 0.01s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
//:TextFileTest                                                 (cached) PASSED in 0.3s

Executed 0 out of 1 test: 1 test passes.
INFO: Build completed successfully, 1 total action
请注意,在runfiles.rlocation("__main__/text.txt")中,__main__是工作区名称,默认情况下为__main__。如果工作区文件中有workspace(name = "workspace name"),则工作区名称将从中设置。

相关文章