Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring 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 introduce the PowerMockito API and look at 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:


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

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

Here is how we'll define the collaborating class, whose constructors and final methods will be mocked:

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, we set an expectation saying that whenever the no-arg constructor of that class is invoked, a mock instance should be returned rather than a real one:


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

CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();

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:

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.

Here's how we'll declare this class:

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:


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:

  .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);

Now it's time to run 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.

These 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 been called:


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   

5. Partial Mocking

Instead of mocking an entire class, the PowerMockito API allows for mocking part of it using the spy method.

This 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, we use the PowerMockito API to partially mock the CollaboratorForPartialMocking class and set an expectation for its static method:

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

The static method is then executed:

returnValue = CollaboratorForPartialMocking.staticMethod();

The mocking behavior is verified:


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 demonstrate the mocking of both the final and private methods.

We will deal with the final method now by setting an expectation and invoking the method:

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

The behavior of partially mocking that method is proved:


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 called by other ones from the same class. In the CollaboratorForPartialMocking class, the privateMethod method is 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:


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 article introduced 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.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Junit footer banner
Comments are closed on this article!