当我执行多个 JUnit 测试时,我发现静态 block 只运行一次。 如何强制它针对每种测试方法运行?我使用的是最新的 JUnit 4.8.2
另外,根据xUnit的设计原则,每个方法都应该完全独立于其他方法。为什么静态 block 只执行一次?
@Test TestMethod1 () {
Accounts ac = new Accounts();
ac.method1(); //kill the thread inside
}
@Test TestMethod2 () {
Accounts ac = new Accounts();
ac.method2(); // the thread is no longer available!!
}
class Accounts {
static {
// initalize one thread to monitor something
}
}
即使 TestMethod1 和 TestMethod2 在不同的测试类中,也会发生这种情况。
最佳答案
静态 block 仅在类加载时执行,因为这就是它们:类初始化器。要多次运行静态 block ,您需要卸载该类(这不是一件容易的事......)。
如果需要使用静态 block ,可以想办法测试一下。为什么不将 block 解包为公共(public)(静态)方法?在那个世界中,您所要做的就是测试方法:
static {
staticInitMethod();
}
public static void staticInitMethod(){
//insert initialization code here
}
你也可以只用一个普通的初始化器就可以逃脱
{//not static
//insert initialization code here
}
虽然,事实是大多数代码根本不需要使用这样的初始化程序。
编辑:原来 Oracle 喜欢静态方法方法 http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
关于java - 如何强制在每个测试方法中运行静态 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5784277/