gpt4 book ai didi

java - 如何模拟使用 PowerMock 进行测试的私有(private)方法?

转载 作者:IT老高 更新时间:2023-10-28 20:21:53 31 4
gpt4 key购买 nike

我有一个类,我想用一个调用私有(private)方法的公共(public)方法对其进行测试。我想假设私有(private)方法可以正常工作。例如,我想要 doReturn....when... 之类的东西。我发现有possible solution using PowerMock ,但是这个解决方案对我不起作用。怎么做?有人遇到过这个问题吗?

最佳答案

我认为这里没有问题。通过使用 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;
}
}

这是 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();
}
}

关于java - 如何模拟使用 PowerMock 进行测试的私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7803944/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com