Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force the static block running in each test method?

I found static block is running only once when I execute multiple JUnit tests. How can I force it to run for each test method? I am using latest JUnit 4.8.2

Also, according to xUnit design principle, every method should be totally independent on others. Why static block only be executed once?

@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
   }
}

This even happens when TestMethod1 and TestMethod2 are in the different Test Classes.

like image 913
user705414 Avatar asked Apr 25 '11 23:04

user705414


People also ask

How do static blocks get executed if there are multiple static blocks?

Execution of static blocks Static blocks are executed before the main() method. Static blocks are executed only once as the class file is loaded to memory. A class can have any number of static initialization blocks. The execution of multiple static blocks will be in the same sequence as written in the program.

Can you mock a static block?

So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it staticInit . This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock staticInit with JMockit to not do anything.


1 Answers

static blocks are only executed on class loading because that is what they are: class initializers. To have a static block run multiple times would require you to unload the class (not an easy thing to do...).

If you need to use static blocks, you can come up with ways to test them. Why not unwrap the block into a public (static) method? All you have to do in that world is test the method:

 static {
      staticInitMethod();
 }

 public static void staticInitMethod(){
      //insert initialization code here
 }

you also might be able to get away with just an ordinary initializer

 {//not static
      //insert initialization code here
 }

Although, the truth is most code doesn't need to use initializers like this at all.

Edit: Turns out Oracle likes the static method approach http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

like image 123
Philip JF Avatar answered Oct 13 '22 23:10

Philip JF