Surefire Maven 插件中的分叉:使用分叉安全吗?

Forking in Surefire Maven Plugin: is it safe to use forking?

我们在 Maven Surefire 插件中有 several options 来描述分叉。其中一个选项,forkCount,解释如下:

Option to specify the number of VMs to fork in parallel in order to execute the tests. When terminated with "C", the number part is multiplied with the number of CPU cores. Floating point value are only accepted together with "C". If set to "0", no VM is forked and all tests are executed within the main process.

基于此,我可能会猜测,如果使用了一个分叉机制,并且复用了分叉 (reuseForks=true),那么同一个 JVM 将用于多个测试。这意味着,如果我已经将一些 class 加载到内存中,那么 class 的静态成员可以在其他一些测试中重用并且意外失败。

我的理解正确吗?

你是对的。使用静态元素的测试不是线程安全的,应该是 excluded from parallel execution:

If the Suite or Parameterized is annotated with @NotThreadSafe, the suite classes are executed in single thread. You can also annotate individual test class referenced by Suite, and the other unannotated test classes in the Suite can be subject to run in parallel.

Note: As designed by JUnit runners, the static methods annotated with @BeforeClass and @AfterClass are called in parent thread. Assign classes to the @NotThreadSafe Suite to prevent from this trouble.