3

我们正在开发一个 Java 命令行应用程序,我们希望对其应用来自许多外部(属性)文件的数据驱动测试,并允许一些知识渊博的用户在不接触 Java 代码库的情况下添加测试。当然,我们要确保每次运行应用程序时,它都是从干净的状态开始的(即没有静态类副作用,干净的文件环境......)。以下是一些选项:

(a) 在单个 JUnit 类的单个方法中运行所有测试,调用应用程序的 main() 方法:

@Test
public void appTest () {
    <get all properties files>
    <for each property file>
        String[] args = <construct command line from property file>
        MyApp.main (args);
        <test result>
     ...
}

不起作用,因为整个事情都在单个 JVM 中运行。

(b) 在一个方法中运行所有的测试 fork 应用程序:

@Test
public void appTest () {
    <get all properties files>
    <for each property file>
        String[] args = <construct command line from property file>
        <fork app with args>
        <test result>
     ...
}

确实为我们提供了单独的 JVM,但 JUnit(和 Surefire)不知道各个测试,因此报告非常无用。

(c) 每个 JUnit 类一个测试:

public class MyAppTest1 {
private static final String PROP_FILE = "src/test/resources/myapp/myapp1.properties
@Test
public void appTest () {
       String[] args = <construct command line from PROP_FILE>
        MyApp.main (args);
        <test result> 
}

}

这可行,但它很麻烦且重复,您必须为每个测试添加一个类。

(d) JUnit 参数化测试 (@RunWith(Parameterized.class) 没有用,因为它们在同一个 JVM 中运行。

(e) Surefire 并行化在 JVM 内。

我们显然在这里遗漏了一些东西,因为我们的测试情况并不少见!任何建议都非常感谢。

4

1 回答 1

0

至少部分回答:Surefire 支持对每个测试用例进行分叉。在您的万无一失的配置部分尝试以下操作:

<reuseForks>false<reuseForks>
<forkCount>1<forkCount>

阅读更多关于http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html

对于“数据驱动测试”的一般问题,最好是自定义 Junit 运行器。这并不像您想象的那么难,只需查看 Junit 源代码中的 runners 包 https://github.com/junit-team/junit/tree/master/src/main/java/org/junit/ runners并使用外部数据重新实现/扩展 Parameterized Runner。

于 2014-10-20T08:56:03.877 回答