Wednesday, August 8, 2018

Mocking of static method in unit testing

While we do unit testing, we mostly encounter the situation where we need to do the unit testing of a method which is calling a static method. if we are using mockito for doing mocking, We will have to suffer as mockito don't provide Static method mocking.

Let's see in a simple manner what is required and how we achieve it.

# Objective: We need to mock the static class which is being used in a method for which we are writing unit test.

# Solution: We have to use Powermockito for that 

What is PowerMockito?
PowerMockito is a PowerMock’s extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.

Getting Start with Powermockito

Also read: JUnit Tests Basics and how to do unit testing in java

First, you need to add the dependency in pom.xml

Now as you are using powermockito , you need to change the JUNIT Runner class as
<StaticClassName> will be replace with you static class Name.

Now let see the example.

Project Structure
Now let see the class for with we will write test case.

public class Rectangle {
 public int getAreaOfRectangle(int length , int breadth) {
  return AreaFinder.findArea("rectangle", length, breadth);


The Static Class

public class AreaFinder {
 public static int findArea(String type , int length , int breadth) {
  if(type.equals("rectangle")) {
   return length*breadth;
  }else if(type.equals("square")) {
   return length*length;
  }else {
   return 0;



Test Class

@PrepareForTest(AreaFinder.class)      // need to add the static class for which you mock the method
public class RectangleTest {

 public void getAreaOfRectangleTest() {
  Rectangle rec = new Rectangle();
  int length =10;
  int breadth =20;

  PowerMockito.mockStatic(AreaFinder.class);   // mocking of static class
  PowerMockito.when(AreaFinder.findArea("rectangle", length, breadth)).thenReturn(200); // defining behaviour
  Assert.assertEquals(200, rec.getAreaOfRectangle(length, breadth));


When you run this you will be able to see the test will be run successfully and it will get passed.

If you have any issue regarding the above concept, please let us know.

I hope this will help you in understand how to do mocking of static method in  unit testing.

Thanks for reading


Post a Comment