gpt4 book ai didi

java - 使用 Ant 中的 JUnit 在单独的 VM 中运行 的每个测试

转载 作者:行者123 更新时间:2023-12-02 03:38:37 26 4
gpt4 key购买 nike

我有一个 Ant 构建文件,它使用 junit 的 batchtest 来测试所有测试类。

假设我有课

class MyTest{
@BeforeClass
public static void setUpBeforeClass(){
//some stuff
}

@Test
public void test1(){
}

@Test
public void test2(){
}
}

我知道 JUnit 为每个测试方法创建一个 MyTest 类的新实例,但我想要的是应该为每个测试方法创建一个新的 VM。我希望每个测试方法在单独的虚拟机中运行,并希望类加载器为每个测试方法再次加载 MyTest 。这可能吗?

我尝试阅读文档并尝试此解决方案:

<junit fork="yes" reloading="true" forkmode="perTest">
<batchtest>
</batchtest>
</junit>

但即使在为每个测试方法使用这些选项之后,setUpBeforeClass 方法也仅被调用一次。我做错了什么吗?

编辑:

我为什么要这样做?

我的测试方法正在使用一些使用static内容的协作者,我希望在每个方法上清除static内容。实际上,我面临着一个问题,测试在本地环境中通过,但在生产中失败

最佳答案

我可以看到工作的唯一可能的方法是拥有 <test> 的多个实例。元素。

问题在于您必须为每个 <test> 指定元素你想要运行什么方法。我创建了一个测试类,其中有一个静态初始化程序和两个测试。具有以下<junit>任务我能够做你想做的事:

<junit fork="yes">
<classpath>
<path refid="classpath" />
</classpath>
<formatter type="xml"/>
<test name="TestSimple" methods="testOne" toDir="firstRun" />
<test name="TestSimple" methods="testTwo" toDir="secondRun" />
</junit>

从我从构建日志中得到的信息来看,很明显它们在两个不同的 JVM 中运行:

test:
...
[junit] Executing 'C:\Program Files\Java\jdk1.7.0_25\jre\bin\java.exe' with arguments:
[junit] '-classpath'
...
[junit] 'org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner'
[junit] 'TestSimple'
[junit] 'methods=testOne'
...
[junit] Executing 'C:\Program Files\Java\jdk1.7.0_25\jre\bin\java.exe' with arguments:
[junit] '-classpath'
...
[junit] 'org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner'
[junit] 'TestSimple'
[junit] 'methods=testTwo'
...
[junit] Test TestSimple FAILED

我还看到了 System.out我在每个测试报告中放入静态初始值设定项的声明。

这里重要的细节是你必须使每个 <test>标签使用属性toDir将其报告重定向到不同的目录。或使用属性 outfile 更改输出文件的名称。这是因为报告文件名使用类的名称,而不是您正在运行的方法。这意味着第二次运行将覆盖第一次运行的报告。

根据您的具体情况,您可以使用 <batchtest>到所有可以在同一个 JVM 中运行而不会出现问题的测试,并添加 <exclude>标记以避免运行有问题的测试。然后添加具体的<test>每个有问题的测试的标签。

他们这样做是因为methods属性专门设计用于重新运行运行速度太慢的特定方法或单独的测试。来自 documentation :

The methods attribute can be useful in the following scenarios:

  • A test method has failed and you want to re-run the test method to test a fix or re-run the test under the Java debugger without having to wait for the other (possibly long running) test methods to complete.
  • One or more test methods are running slower than expected and you want to re-run them under a Java profiler (without the overhead of running the profiler whilst other test methods are being executed).

但就我个人而言,并且来自一个与您之前遇到相同问题的人,静态初始化器很糟糕!我会非常努力地尽快摆脱它们。引用 @PeterNiederwieser 的话,为每组测试使用一个新的 JVM 将使您的测试套件运行速度非常慢!

关于java - 使用 Ant 中的 JUnit 在单独的 VM 中运行 <batchtest> 的每个测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com