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

标签 java unit-testing junit

当我执行多个 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
   }
}

即使 TestMethod1TestMethod2 在不同的测试类中,也会发生这种情况。

最佳答案

静态 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/

相关文章:

java - 如何查找字符串中第n次出现的字符?

java - 如何设置 org.eclipse.swt.widgets.Text 边框的颜色

java - JTextField 不读取用户输入的数据

java - 如何将连接返回到池

ios - 单元测试 UICollectionView.indexPath(: UICollectionViewCell)

angular - 使用 Jasmine 测试 Angular queryParams

java - @org.testng.annotations.Test 和 @org.junit.Test 问题

java - 如何在 Java 中保存 shell 脚本的 echo 输出

c++ - 有没有办法检测升压单元测试二进制文件中有哪些测试

java - 如何找到 "Could not resolve placeholder"原因