如何使用PowerMock模拟私有方法进行测试?

Jul*_*ump 59 java testing junit mockito powermock

我有一个类,我想用一个调用私有的公共方法测试.我想假设私有方法正常工作.例如,我喜欢类似的东西doReturn....when....我发现有可能使用PowerMock的解决方案,但这个解决方案对我不起作用.怎么做?有没有人有这个问题?

Bri*_*ice 93

我这里没有看到问题.使用Mockito API使用以下代码,我设法做到了这一点:

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是JUnit测试:

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.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

        spy.meaningfulPublicApi();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于其IDE内容中有Hamcrest匹配器类的其他开发人员,请注意:它们不适用于Mockito的.withArguments()方法 - 您必须使用Mockito匹配器!;)花了一些时间来弄清楚为什么异常会被我的测试代码抛出. (6认同)
  • 感谢您的回答,他们维基上的示例代码仅显示了使用EasyMock后端的API,而不是Mockito. (3认同)

Sle*_*led 21

可以与任何测试框架一起使用的通用解决方案(如果您的类是非类final)是手动创建自己的模拟.

  1. 将您的私人方法更改为受保护.
  2. 在您的测试类中扩展该类
  3. 覆盖先前的私有方法以返回您想要的任何常量

这不使用任何框架,因此它不那么优雅,但它总能工作:即使没有PowerMock.或者,如果你已经完成了步骤#1,你可以使用Mockito为你做第2步和第3步.

要直接模拟私有方法,您需要使用PowerMock,如另一个答案中所示.

  • 这是一种可行的方法,但为了测试而更改代码是一个错误的决定 (2认同)