Powermock – How to mock static, private methods (Powermock tutorial)

This tutorial tries to explain how to use Powermock to mock static and private methods.

Powermock is an awesome framework that extends mock frameworks like Mockito etc.,

Other testing tutorials:
How to mock static, private methods (Powermock tutorial)
Unit testing void methods using verify and ArgumentCaptor
Mockito Deep Stubs Example
Selenium based automated test using Java, JUNIT and Maven – Example

When you’ve situations where you need to mock static or private methods, Powermock comes handy and useful. It’s better than modifying code under test.

Code under test – ExamplePojo.java


package com.idodevjobs;

public class ExamplePojo {

    public String methodMakingPrivateMethodCall(String message) {
        return privateMethod(message);
    }

    public String methodMakingStaticNonVoidMethodCall(String message) {
        return ExampleUtil.sayHello(message);
    }

    public String methodMakingStaticVoidMethodCall(String message) {
        ExampleUtil.printHello(message);
        return "printed " + message;
    }

    private String privateMethod(String helloMessage) {
        return "another " + helloMessage;
    }
}

Dependent static class – ExampleUtil.java


package com.idodevjobs;

public class ExampleUtil {

    public static String sayHello(String message) {
        return "Hello " + message;
    }

    public static void printHello(String message) {
        System.out.println("printing .. " + message);
    }
}

jUnit – ExamplePojoTest.java


package com.idodevjobs;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ExampleUtil.class, ExamplePojo.class})
public class ExamplePojoTest {

    @Test
    public void testMethodMakingPrivateMethodCall() throws Exception {
        ExamplePojo spyExamplePojo = PowerMockito.spy(new ExamplePojo());
        when(spyExamplePojo, method(ExamplePojo.class, "privateMethod", String.class)).withArguments(anyString()).thenReturn("test test");
        String result = spyExamplePojo.methodMakingPrivateMethodCall("test");
        assertEquals("test test", result);
    }

    @Test
    public void testMethodMakingStaticNonVoidMethodCall() throws Exception {
        mockStatic(ExampleUtil.class);
        when(ExampleUtil.sayHello(anyString())).thenReturn("test test");
        String result = new ExamplePojo().methodMakingStaticNonVoidMethodCall("test");
        assertEquals("test test", result);
    }

    @Test
    public void testMethodMakingStaticVoidMethodCall() throws Exception {
        mockStatic(ExampleUtil.class);
        doNothing().when(ExampleUtil.class);
        new ExamplePojo().methodMakingStaticVoidMethodCall("test");
    }
}

maven – pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.idodevjobs</groupId>
    <artifactId>junit-powermock-mockito-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>junit-powermock-mockito-example</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.6.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.6.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Using Powermock

The jUnit classes that use Powermock need to have 2 annotations – @RunWith(PowerMockRunner.class) and @PrepareForTest({ExampleUtil.class, ExamplePojo.class}).

@RunWith PowerMockRunner tells jUnit to use the powermock’s custom jUnit runner to execute the test cases.

@PrepareForTest annotation should include the classes that need to be mocked using Powermock for Powermock to be able to prepare, manipulate the byte code and instrument.

Mocking private method using partial mocking (spy)

Powermock’s spy can be used to create partial mocks.

When a class is spied, real methods are called unless it’s mocked.

In this case, the class under test (ExamplePojo) is spied so that private methods are mocked and the actual methods are called otherwise.

Mocking static non-void method

mockStatic method is used to mock static classes.

when method is used to mock the static non-void methods.

Mocking static void method

doNothing method is used along with mockStatic to mock static void methods.

Please leave a comment if you have any questions. Please share and comment if you find this useful.

Advertisements
This entry was posted in java and tagged , , . Bookmark the permalink.

4 Responses to Powermock – How to mock static, private methods (Powermock tutorial)

  1. Pingback: Mockito Example – Unit testing void methods using verify and ArgumentCaptor | iDoDevJobs

  2. Pingback: Getting Started: Selenium (ChromeDriver) based UI automated test using Java, JUNIT and Maven – Example | iDoDevJobs

  3. Pingback: Mockito Deep Stubs Example | iDoDevJobs

  4. tukaram says:

    I am always getting IllegalArgumentException: argument type mismatch while trying all those suggestions out there on google. Could you please help me. I am passing correct arguments though.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s