I am facing an issue while mocking a static member in my project. Please find below example which is similar to my project code.
class A {
private String place = null;
public methodA() {
this.place = LoadPlaceDao.placeDao.PlaceMap();
.........
.........
.........
}
}
public class LoadPlaceDao {
public static PlaceDao placeDao;
public LoadPlaceDao() {
placeDao = new PlaceDaoImpl();
}
}
the main objective my test is code coverage only, I am trying to mock LoadPlaceDao.placeDao.PlaceMap(); Getting NullPointerException near LoadPlaceDao.placeDao so remaining lines are not covering. PowerMockito will work only for static methods. **placeDao is static reference.
PowerMock is a JUnit extension the leverages the possibilities of EasyMock and Mockito to mock static methods (and much more).
Our unit under test is the class Calculator which just delegates the addition of two integers to MathUtil which offers only static methods:
public class Calculator {
public int add(int a, int b) {
return MathUtil.addInteger(a, b);
}
}
public abstract class MathUtil {
public static final int addInteger(int a, int b) {
return a + b;
}
private MathUtil() {}
}
For some obscure reason, we want to mock the MathUtil because in our test scenario the addition should yield other results than it would normally do (in real life we may mock a webservice call or database access instead). How can t
his be achieved? Have a look at the following test:
@RunWith(PowerMockRunner.class)
@PrepareForTest( MathUtil.class )
public class CalculatorTest {
/** Unit under test. */
private Calculator calc;
@Before public void setUp() {
calc = new Calculator();
PowerMockito.mockStatic(MathUtil.class);
PowerMockito.when(MathUtil.addInteger(1, 1)).thenReturn(0);
PowerMockito.when(MathUtil.addInteger(2, 2)).thenReturn(1);
}
@Test public void shouldCalculateInAStrangeWay() {
assertEquals(0, calc.add(1, 1) );
assertEquals(1, calc.add(2, 2) );
}
}
First of all, we use a special test runner provided by the PowerMock framework. With the @PrepareForTest( MathUtil.class ) annotation our class to mock is prepared. This annotation takes a list of all the classes to mock. In our example, this list consists of a single item MathUtil.class.
In our setup method we call PowerMockito.mockStatic(...). (We could have written a static import for the method mockStatic, but that way you can more clearly see where that methods come from.)
Then we define our mock behaiviour calling PowerMockito.when(...). In our tests we have the usual assertions.