代码之家  ›  专栏  ›  技术社区  ›  Zeitgeist

如何从单个java_test()规则运行Bazel中的所有测试?

  •  10
  • Zeitgeist  · 技术社区  · 8 年前

    4 回复  |  直到 8 年前
        1
  •  7
  •   Natan    7 年前

    在里面 Bazel here . 它很短很直接,你可以把它复制到你的项目中或者做类似的事情。

    java_library(
        name = "tests",
        testonly = 1,
        srcs = glob(["*.java"])
    )
    
    java_test(
       name = "MyTests",
       test_class = "MyTests",
       runtime_deps = [":tests"],
    )
    

    还有我的测试。java文件应如下所示:

    import package.ClasspathSuite;
    
    import org.junit.runner.RunWith;
    
    @RunWith(ClasspathSuite.class)
    public class MyTests { } 
    
        2
  •  4
  •   Adam    8 年前

    您可以编写一个JUnit测试套件类,该类将运行其他测试。例如,如果您有测试类Test1。java和Test2。java,您可以这样做:

    所有测试。Java语言

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    import org.junit.runners.Suite.SuiteClasses;
    
    @RunWith(Suite.class)
    @SuiteClasses({
        Test1.class,
        Test2.class
    })
    public class AllTests {}
    

    构建

    java_test(
        name = "AllTests",
        test_class = "AllTests",
        srcs = [
            "AllTests.java",
            "Test1.java",
            "Test2.java",
        ],
    )
    

    如果不想在测试套件中指定测试类名,可以通过反射进行操作。以下示例假设您的所有测试都在“com.foo”包中,并且所有测试都是java\u测试规则的SRC:

    package com.foo;
    
    import java.io.File;
    import java.io.IOException;
    import java.net.URLClassLoader;
    import java.util.Enumeration;
    import java.util.Set;
    import java.util.TreeSet;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import junit.framework.JUnit4TestAdapter;
    import junit.framework.TestSuite;
    import org.junit.runner.RunWith;
    
    @RunWith(org.junit.runners.AllTests.class)
    public class AllTests {
      public static TestSuite suite() throws IOException {
        TestSuite suite = new TestSuite();
        URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
        // The first entry on the classpath contains the srcs from java_test
        findClassesInJar(new File(classLoader.getURLs()[0].getPath()))
            .stream()
            .map(c -> {
              try {
                return Class.forName(c);
              } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
              }
            })
            .filter(clazz -> !clazz.equals(AllTests.class))
            .map(JUnit4TestAdapter::new)
            .forEach(suite::addTest);
        return suite;
      }
    
      private static Set<String> findClassesInJar(File jarFile) {
        Set<String> classNames = new TreeSet<>();
        try {
          try (ZipFile zipFile = new ZipFile(jarFile)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
              String entryName = entries.nextElement().getName();
              if (entryName.startsWith("com/foo") && entryName.endsWith(".class")) {
                int classNameEnd = entryName.length() - ".class".length();
                classNames.add(entryName.substring(0, classNameEnd).replace('/', '.'));
              }
            }
          }
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        return classNames;
      }
    }
    
        3
  •  3
  •   Zeitgeist    8 年前

    这里有一个不需要使用Suite的解决方案。

    .处理所有测试的bzl宏:

    def run_tests(name, srcs, package, deps):
      for src in srcs:
        src_name = src[:-5]
        native.java_test(name=src_name, test_class=package + "." + src_name, srcs=srcs, deps=deps, size="small")
    

    run_tests(
        name = "test",
        srcs = glob(["*Test.java"]),
        package = "pkg",
        deps = [
            ":src_lib",
        ]
    )
    
        4
  •  1
  •   M. Leonhard    6 年前

    Gerrit项目包含一个名为 junit_tests . 它获取src列表并生成一个 AllTestsTestSuite.java java_test 包括生成的java文件和所有指定源、DEP等的目标。下面介绍如何设置它。

    首先将这些行添加到 WORKSPACE 文件:

    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")
    
    

    现在将此添加到 BUILD 文件:

    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",
        ],
    )
    

    构建 文件位于 $WORKSPACE_ROOT/javatests/com/company/a_package/BUILD 然后,您可以使用以下工具运行这些特定测试:

    bazel test //javatests/com/company/a_package:AllTests
    

    bazel test //javatests/...
    

    如果您的目录包含 .java

    /** Workaround for https://github.com/bazelbuild/bazel/issues/2539 */
    @Test
    public void emptyTest() {}
    

    这对我来说是在MacOS上使用Bazel 2.0.0。我还可以使用Bazel插件在IntelliJ 2019.2中运行测试。