如何使用 powermock 模拟私有方法?

How to mock private method using powermock?

如果我有一个简单的 class 比如:

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

mock私有方法getDefault Lucky Number需要做哪些修改? 我有这个不起作用

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

模拟工作所需的 PowerMock 注释:

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

工作测试示例:

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 版本:

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