Java 如何将测试类包含到 Maven jar 中并执行它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36047637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:24:23  来源:igfitidea点击:

How can I include test classes into Maven jar and execute them?

javamavenunit-testingmaven-3maven-jar-plugin

提问by jam

In a Maven project, I have test classes and source classes in the same package, but in different physical locations.

在 Maven 项目中,我将测试类和源类放在同一个包中,但位于不同的物理位置。

.../src/main/java/package/** <-- application code
.../src/test/java/package/** <-- test code

It's no problem to access the source classes in the test classes, but I would like to run a test runner in the main method and access the AllTest.classso that I can create jar and execute my tests.

访问测试类中的源类没有问题,但我想在 main 方法中运行一个测试运行器并访问它,AllTest.class以便我可以创建 jar 并执行我的测试。

 public static void main(String[] args) {
    // AllTest not found
    Result result = JUnitCore.runClasses(AllTest.class);
    for (Failure failure : result.getFailures()) {
        System.out.println(failure.toString());
    }
    System.out.println(result.wasSuccessful());
}

But it doesn't work as I don't have access to the test code. I don't understand since they are in the same package.

但它不起作用,因为我无权访问测试代码。我不明白,因为它们在同一个包中。

Question: how can access test classes from application classes? Alternatively, how can Maven package a fat jar including test classes and execute tests?

问题:如何从应用程序类访问测试类?或者,Maven 如何打包包含测试类的胖 jar 并执行测试?

采纳答案by A_Di-Matteo

You should not access test classes from your application code, but rather create a main (the same main) in the test scope and create an additional artifact for your project.

您不应从应用程序代码访问测试类,而应在测试范围内创建一个 main(相同的 main)并为您的项目创建一个额外的工件。

However, in this additional artifact (jar) you would need to have:

但是,在这个额外的工件(jar)中,您需要:

  • The test classes
  • The application code classes
  • External dependencies required by application code (in compilescope)
  • External dependencies required by the test code (in testscope)
  • 测试类
  • 应用程序代码类
  • 应用程序代码所需的外部依赖项(在compile范围内)
  • 测试代码所需的外部依赖项(在test范围内)

Which basically means a fat jar with the addition of test classes (and their dependencies). The Maven Jar Pluginand its test-jargoal would not suit this need. The Maven Shade Pluginand its shadeTestJaroption would not help neither.

这基本上意味着一个添加了测试类(及其依赖项)的胖 jar。在Maven的Jar插件和它的test-jar目标将无法满足这一需求。在Maven的阴影插件和它的shadeTestJar方案不会也不帮助。

So, how to create in Maven a fat jar with test classes and external dependencies?

那么,如何在 Maven 中创建一个带有测试类和外部依赖项的胖 jar 呢?

The Maven Assembly Pluginis a perfect candidate in this case.

在这种情况下,Maven 程序集插件是一个完美的候选者。

Here is a minimal POM sample:

这是一个最小的 POM 示例:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample</groupId>
    <artifactId>sample-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <descriptor>src/main/assembly/assembly.xml</descriptor>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>com.sample.TestMain</mainClass>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

The configuration above is setting the main class defined by you in your test classes. But that's not enough.

上面的配置是在你的测试类中设置你定义的主类。但这还不够。

You also need to create a descriptor file, in the src\main\assemblyfolder an assembly.xmlfile with the following content:

您还需要创建一个描述符文件,在src\main\assembly文件夹中创建一个assembly.xml包含以下内容的文件:

<assembly
    xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>fat-tests</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>test</scope>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/test-classes</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*.class</include>
            </includes>
            <useDefaultExcludes>true</useDefaultExcludes>
        </fileSet>
    </fileSets>
</assembly>

The configuration above is:

上面的配置是:

  • setting external dependencies to be taken from the testscope (which will also take the compilescope as well)
  • setting a filesetto include compiled test classes as part of the packaged fat jar
  • setting a final jar with fat-testsclassifier (hence your final file will be something like sampleproject-1.0-SNAPSHOT-fat-tests.jar).
  • 设置要从test范围中获取的外部依赖项(也将获取compile范围)
  • 设置 afileset以将编译的测试类包含在打包的 fat jar 中
  • 使用fat-tests分类器设置最终 jar (因此您的最终文件将类似于sampleproject-1.0-SNAPSHOT-fat-tests.jar)。

You can then invoke the main as following (from the targetfolder):

然后,您可以调用 main 如下(从target文件夹中):

java -jar sampleproject-1.0-SNAPSHOT-fat-tests.jar


From such a main, you could also invoke all of your test cases as following:

从这样的主,你还可以调用所有的测试用例如下:

  • Create a JUni test suite
  • Add to the test suite the concerned tests
  • Invoke the test suite from your plain Java main
  • 创建 JUni 测试套件
  • 将相关测试添加到测试套件中
  • 从纯 Java 主程序调用测试套件

Example of test suite:

测试套件示例:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ AppTest.class })
public class AllTests {

}

Note: in this case the test suite is only concerning the AppTestsample test.

注意:在这种情况下,测试套件仅与AppTest示例测试有关。

Then you could have a main class as following:

然后你可以有一个主类如下:

import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;

public class MainAppTest {

    public static void main(String[] args) {
        System.out.println("Running tests!");

        JUnitCore engine = new JUnitCore();
        engine.addListener(new TextListener(System.out)); // required to print reports
        engine.run(AllTests.class);
    }
}

The main above would then execute the test suite which will in chain execute all of the configured tests.

然后上面的 main 将执行测试套件,该套件将在链中执行所有配置的测试。