gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:33 25 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/55113895/

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