16

如何让 JUnitClassLoader对其执行的每个测试类使用单独的?

我正在TestRunner为设置大量静态变量的库编写 JUnit。我基本上想在每个测试类之间重置所有这些,而不需要知道它们是什么。我不想与对框架的深入了解相结合,因为每当库在内部发生变化时,我TestRunner就会崩溃。

在我走得更远之前,我想明确表示我真的很想这样做。

  • 我无法控制图书馆。
  • 我没有不使用静态变量的选项。
  • 我不想使用反射或 Powermock,因为我不想知道图书馆里发生了什么。
  • 我不想使用 Maven 配置来分叉测试过程,因为测试实用程序与构建工具相关联。

我在 StackOverflow 上找到的所有其他答案都只是说“不要那样做”,这没有帮助。第一个回答“静态变量是愚蠢的”的人会赢得一个甜甜圈。

4

2 回答 2

13

In the end I wrote my own, loosely based on another Stack Overflow answer (which didn't work for me).

It's now on GitHub, and Maven Central. https://github.com/BinaryTweed/quarantining-test-runner

<dependency>
    <groupId>com.binarytweed</groupId>
    <artifactId>quarantining-test-runner</artifactId>
    <version>0.0.1</version>
</dependency>

To use it annotate your test classes accordingly:

@RunWith(QuarantiningRunner.class)
@Quarantine({"com.binarytweed"})
public class MyIsolatedTest {
...

The linked answer didn't work for me as the test class itself needs to be loaded in a separate ClassLoader, as then all the classes it references will use the same loader. Quarantining is inclusive (rather than exclusive) as you need the JUnit @Test annotations to be loaded by the parent ClassLoader, otherwise JUnit can't find any testable methods as it uses Class<Test> as a key in a lookup map.

于 2015-02-22T11:19:23.520 回答
2

MyFaces 有一个TestPerClassLoaderRunner,它(尽管它的名字)是你正在寻找的。

于 2015-02-17T22:21:36.273 回答