Search This Blog

Thursday, 29 May 2014

Test static methods with JMockit

If you want to use JMockit within Eclipse you have to be aware of several pitfalls. You cannot use the Junit.jar which is integrated into eclipse. You need to download it from the original junit.org site. Further, it is important that the jmockit.jar appears before the Junit jar in the classpath. Go to the  "Order and export" tab of the "Java build path".

Looking now at a very simple example to test static methods:

1:  public class MyStaticClass {  
2:      static boolean doSomethingCrazy() {  
3:          return true;  
4:      }  
5:  }  

The test for this static methods could look as follows:

1:  import static org.junit.Assert.assertFalse;  
2:  import org.junit.*;  
3:  import mockit.*;  
4:  public class StaticTest {  
5:      @Mocked  
6:      MyStaticClass myClass;  
7:      @Test  
8:      public void testMakeConnection(){  
9:          new NonStrictExpectations(){  
10:              // MyStaticClass is mocked here  
11:              {  
12:                  MyStaticClass.doSomethingCrazy();  
13:                  returns(false);  
14:              }  
15:          };  
16:          boolean wasItCrazy = MyStaticClass.doSomethingCrazy();  
17:          assertFalse(wasItCrazy);  
18:          new Verifications() {{  
19:              MyStaticClass.doSomethingCrazy(); times = 1;  
20:          }};  
21:      }  
22:  }  

JMockit appears to be very powerful and elegant. I will publish more examples soon.

No comments:

Post a Comment