如何在每个测试方法中强制运行静态块?

use*_*414 9 java junit unit-testing

我发现当我执行多个JUnit测试时静态块只运行一次.如何强制它为每个测试方法运行?我正在使用最新的JUnit 4.8.2

另外,根据xUnit设计原则,每种方法都应该完全独立于其他方法.为什么静态块只执行一次?

@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
   }
}
Run Code Online (Sandbox Code Playgroud)

TestMethod1TestMethod2位于不同的测试类中时,甚至会发生这种情况.

Phi*_* JF 11

静态块仅在类加载时执行,因为它们是这样的:类初始化器.要让多次运行静态块,需要卸载该类(这不是一件容易的事情......).

如果您需要使用静态块,您可以想出测试它们的方法.为什么不将块解包为公共(静态)方法?你在这个世界所要做的就是测试方法:

 static {
      staticInitMethod();
 }

 public static void staticInitMethod(){
      //insert initialization code here
 }
Run Code Online (Sandbox Code Playgroud)

你也可以通过一个普通的初始化器来逃脱

 {//not static
      //insert initialization code here
 }
Run Code Online (Sandbox Code Playgroud)

虽然,事实是大多数代码都不需要使用像这样的初始化器.

编辑:结果Oracle喜欢静态方法方法http://download.oracle.com/javase/tutorial/java/javaOO/initial.html