【发布时间】:2016-05-27 00:06:50
【问题描述】:
在 Intelij 和 Eclipse IDE(可能还有其他一些 IDE)中,可以运行包中的所有测试类(甚至是项目中的所有测试类),而无需将它们中的每一个显式放入测试套件类( this 是我想避免的)。只需右键单击 -> 运行所有测试,瞧!
不过,我对这种测试方法有一个问题。我想在所有测试完成后进行一些清理,但无论我做什么,似乎都没有任何效果。
起初,我尝试使用RunListener 及其testRunFinished() 方法,但在每次原子测试完成后都会调用它,因此在运行其中许多测试时不是我想要的。
然后我想到了终结器和runFinalizersOnExit(true),不幸的是,它已被弃用并且仅在其中一台执行测试的计算机上工作。
我尝试的最后一件事是创建一个“侦听器”线程,该线程 - 给定测试执行开始和结束时间的差异 - 例如,在测试完成五秒后会清理干净。我使用下面的代码来测试该解决方案:
import org.junit.Test;
public class Main {
static {
System.out.println("In a static block!");
new Thread(new Runnable() {
public void run() {
System.out.println("Starting static thread!");
try {
while (true) {
Thread.sleep(1000);
System.out.println("Static thread working...");
}
} catch (InterruptedException e) {
System.err.println("Static thread interrupted!");
e.printStackTrace();
} catch (Exception e) {
System.err.println("Static thread catches exception!");
e.printStackTrace();
} finally {
System.err.println("Static thread in finally method.");
Thread.currentThread().interrupt();
}
}
}).start();
System.out.println("Exiting static block!");
}
@Test
public void test() throws Exception {
System.out.println("Running test!");
Thread.sleep(3000);
System.out.println("Stopping test!");
}
}
没有运气。测试完成后线程被杀死。甚至finally 块也永远不会执行...
In a static block!
Exiting static block!
Running test!
Starting static thread!
Static thread working...
Static thread working...
Stopping test!
Static thread working...
期望的行为是:
- 右键单击
- 运行所有测试
- TestA 正在运行...
- 测试完成
- TestB 正在运行...
- TestB 完成
- ...更多测试类...
- 清理
【问题讨论】:
标签: java eclipse unit-testing junit code-cleanup