I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Unit testing with the help of a mocking framework has been recognized as a useful practice for a long time, and the Mockito framework, in particular, has dominated this market in recent years.

And in order to facilitate decent code designs and make the public API simple, some desired features have been intentionally left out. In some cases, however, these shortcomings force testers to write cumbersome code just to make the creation of mocks feasible.

This is where the PowerMock framework comes into play.

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.

This tutorial will give an introduction to the PowerMockito API and how it is applied in tests.

2. Preparing for Testing with PowerMockito

The first step to integrate PowerMock support for Mockito is to include the following two dependencies in the Maven POM file:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>

Next, we need to prepare our test cases for working with PowerMockito by applying the following two annotations:

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")

The fullyQualifiedNames element in the @PrepareForTest annotation represents an array of fully qualified names of types we want to mock. In this case, we use a package name with a wildcard to tell PowerMockito to prepare all types within the com.baeldung.powermockito.introduction package for mocking.

Now we are ready to exploit the power of PowerMockito.

3. Mocking Constructors and Final Methods

In this section, we will demonstrate the ways to get a mock instance instead of a real one when instantiating a class with the new operator, and then use that object to mock a final method. The collaborating class, whose constructors and final methods will be mocked, is defined as follows:

public class CollaboratorWithFinalMethods {
    public final String helloMethod() {
        return "Hello World!";
    }
}

First, we create a mock object using the PowerMockito API:

CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);

Next, set an expectation telling that whenever the no-arg constructor of that class is invoked, a mock instance should be returned rather than a real one:

whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);

Let’s see how this construction mocking works in action by instantiating the CollaboratorWithFinalMethods class using its default constructor, and then verify the behaviors of PowerMock:

CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();

In the next step, an expectation is set to the final method:

when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");

This method is then executed:

String welcome = collaborator.helloMethod();

The following assertions confirm that the helloMethod method has been called on the collaborator object, and returns the value set by the mocking expectation:

Mockito.verify(collaborator).helloMethod();
assertEquals("Hello Baeldung!", welcome);

If we want to mock a specific final method rather than all the final ones inside an object, the Mockito.spy(T object) method may come in handy. This is illustrated in section 5.

4. Mocking Static Methods

Suppose that we want to mock static methods of a class named CollaboratorWithStaticMethods. This class is declared as follows:

public class CollaboratorWithStaticMethods {
    public static String firstMethod(String name) {
        return "Hello " + name + " !";
    }

    public static String secondMethod() {
        return "Hello no one!";
    }

    public static String thirdMethod() {
        return "Hello no one again!";
    }
}

In order to mock these static methods, we need to register the enclosing class with the PowerMockito API:

mockStatic(CollaboratorWithStaticMethods.class);

Alternatively, we may use the Mockito.spy(Class<T> class) method to mock a specific one as demonstrated in the following section.

Next, expectations can be set to define the values methods should return when invoked:

when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()))
  .thenReturn("Hello Baeldung!");
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");

Or an exception may be set to be thrown when calling the thirdMethod method:

doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
CollaboratorWithStaticMethods.thirdMethod();

Now, it is time for executing the first two methods:

String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");

Instead of calling members of the real class, the above invocations are delegated to the mock’s methods. The following assertions prove that the mock has come into effect:

assertEquals("Hello Baeldung!", firstWelcome);
assertEquals("Hello Baeldung!", secondWelcome);

We are also able to verify behaviors of the mock’s methods, including how many times a method is invoked. In this case, the firstMethod has been called twice, while the secondMethod has never:

verifyStatic(Mockito.times(2));
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
        
verifyStatic(Mockito.never());
CollaboratorWithStaticMethods.secondMethod();

Note: The verifyStatic method must be called right before any static method verification for PowerMockito to know that the successive method invocation is what needs to be verified.

Lastly, the static thirdMethod method should throw a RuntimeException as declared on the mock before. It is validated by the expected element of the @Test annotation:

@Test(expected = RuntimeException.class)
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
    // other methods   
       
    CollaboratorWithStaticMethods.thirdMethod();
}

5. Partial Mocking

Instead of mocking an entire class, the PowerMockito API allows for mocking part of it using the spy method. The following class will be used as the collaborator to illustrate the PowerMock support for partial mocking:

public class CollaboratorForPartialMocking {
    public static String staticMethod() {
        return "Hello Baeldung!";
    }

    public final String finalMethod() {
        return "Hello Baeldung!";
    }

    private String privateMethod() {
        return "Hello Baeldung!";
    }

    public String privateMethodCaller() {
        return privateMethod() + " Welcome to the Java world.";
    }
}

Let’s begin with mocking a static method, which is named staticMethod in the above class definition. First, use the PowerMockito API to partially mock the CollaboratorForPartialMocking class and set an expectation for its static method:

spy(CollaboratorForPartialMocking.class);
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");

The static method is then executed:

returnValue = CollaboratorForPartialMocking.staticMethod();

The mocking behavior is verified as follows:

verifyStatic();
CollaboratorForPartialMocking.staticMethod();

The following assertion confirms that the mock method has actually been called by comparing the return value against the expectation:

assertEquals("I am a static mock method.", returnValue);

Now it is time to move on to the final and private methods. In order to illustrate the partial mocking of these methods, we need to instantiate the class and tell the PowerMockito API to spy it:

CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
CollaboratorForPartialMocking mock = spy(collaborator);

The objects created above are used to demonstrating the mocking of both the final and private methods. We will deal with the final method now by setting an expectation and invoke the method:

when(mock.finalMethod()).thenReturn("I am a final mock method.");
returnValue = mock.finalMethod();

The behavior of partially mocking that method is proved:

Mockito.verify(mock).finalMethod();

A test verifies that calling the finalMethod method will return a value that matches the expectation:

assertEquals("I am a final mock method.", returnValue);

A similar process is applied to the private method. The main difference is that we cannot directly invoke this method from the test case. Basically, a private method is to be called by other ones from the same class. In the CollaboratorForPartialMocking class, the privateMethod method is to be invoked by the privateMethodCaller method and we will use the latter as a delegate. Let’s start with the expectation and invocation:

when(mock, "privateMethod").thenReturn("I am a private mock method.");
returnValue = mock.privateMethodCaller();

The mocking of the private method is confirmed:

verifyPrivate(mock).invoke("privateMethod");

The following test makes sure that the return value from invocation of the private method is the same as the expectation:

assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);

6. Conclusion

This tutorial has provided an introduction to the PowerMockito API, demonstrating its use in solving some of the problems developers encounter when using the Mockito framework.

The implementation of these examples and code snippets can be found in the linked GitHub project.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS