如何在真正的分叉VM中执行测试的每个方法? VM真正意味着关闭(并且触发了关闭挂钩),并且VM之间不共享系统属性。
我使用以下Maven surefire配置。
<configuration>
<reuseForks>false</reuseForks>
<parallel>methods</parallel>
<threadCount>1</threadCount>
<perCoreThreadCount>false</perCoreThreadCount>
</configuration>
以下测试。
public class ConcurrentIT {
private static void test(String counter) throws InterruptedException {
Runtime.getRuntime().addShutdownHook(
new Thread(() -> System.out.println("Checks if the shutdown hooks are triggered"))
);
System.out.println("PID is " + ManagementFactory.getRuntimeMXBean().getName()
+ " with the property before " + System.getProperty("toto"));
System.setProperty("toto", counter);
TimeUnit.SECONDS.sleep(1L);
System.out.println("Counter is " + counter
+ " and the property value is " + System.getProperty("toto"));
}
@Test
public void one() throws InterruptedException {
test("1");
}
@Test
public void two() throws InterruptedException {
test("2");
}
@Test
public void three() throws InterruptedException {
test("3");
}
@Test
public void four() throws InterruptedException {
test("4");
}
}
预期输出应如下所示(并使用Intellij的fork选项工作)。
PID is 94969@Nicolass-MacBook-Pro.local with the property before null
Counter is 1 and the property value is 1
Checks if the shutdown hooks are triggered
PID is 94971@Nicolass-MacBook-Pro.local with the property before null
Counter is 2 and the property value is 2
Checks if the shutdown hooks are triggered
PID is 94972@Nicolass-MacBook-Pro.local with the property before null
Counter is 4 and the property value is 4
Checks if the shutdown hooks are triggered
PID is 94973@Nicolass-MacBook-Pro.local with the property before null
Counter is 3 and the property value is 3
Checks if the shutdown hooks are triggered
虽然目前的输出如下。
PID is 95773@Nicolass-MacBook-Pro.local with the property before null
Counter is 1 and the property value is 1
PID is 95773@Nicolass-MacBook-Pro.local with the property before 1
Counter is 2 and the property value is 2
PID is 95773@Nicolass-MacBook-Pro.local with the property before 2
Counter is 4 and the property value is 4
PID is 95773@Nicolass-MacBook-Pro.local with the property before 4
Counter is 3 and the property value is 3