本文介紹了如何通過Bazel從JUnit測試執(zhí)行中找到指向Java源代碼文件的路徑的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想通過JUnit測試檢查我們的monorepo代碼庫中的一個文本文件。JUnit測試通過bazel test
命令執(zhí)行。如何將Bazel配置為將源代碼目錄路徑(而不是緩存的編譯JAR文件路徑)傳遞給單元測試?它可以是CLI參數(shù)、環(huán)境變量等。
推薦答案
要做到這一點,一種方法是使用data
屬性,該屬性使文件在運行時可用于測試(和其他二進制文件),而對于Java,Bazel提供了用于查找數(shù)據文件的運行文件庫。例如:
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__
是工作區(qū)名稱,默認情況下為__main__
。如果工作區(qū)文件中有workspace(name = "workspace name")
,則工作區(qū)名稱將從中設置。
這篇關于如何通過Bazel從JUnit測試執(zhí)行中找到指向Java源代碼文件的路徑的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,