Skip to content
Advertisement

How to mock private method using powermock?

If I have a simple class like:

public class LuckyNumberGenerator {
    public int getLuckyNumber(String name) {
        return getDefaultLuckyNumber();
    }
    private int getDefaultLuckyNumber() { }
}

What modification do I need to mock the private method getDefaultLuckyNumber? I have this which doesnt work

LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
when(mock, "getDefaultLuckyNumber").thenReturn(300);

Advertisement

Answer

PowerMock annotations required for mock working:

@RunWith(PowerMockRunner.class)
@PrepareForTest(LuckyNumberGenerator.class)

Example of working test:

import org.junit.Assert;
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.powermock.api.mockito.PowerMockito.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(LuckyNumberGenerator.class)
public class ServiceTest {
    @Test
    public void test() throws Exception {
        LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
        PowerMockito.when(mock, "getDefaultLuckyNumber").thenReturn(300);
        Assert.assertEquals(300, mock.getLuckyNumber("name"));
    }
}

public class LuckyNumberGenerator {
    public int getLuckyNumber(String name) {
        return getDefaultLuckyNumber();
    }
    private int getDefaultLuckyNumber() {
        return 1;
    }
}

PowerMock version:

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement