0

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

4

1 回答 1

0

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

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

请注意,inrunfiles.rlocation("__main__/text.txt")__main__工作区名称,默认情况下是__main__. 如果workspace(name = "workspace name")WORKSPACE 文件中有一个,则工作空间名称将从该文件中设置。

于 2022-01-05T03:52:11.763 回答