如何模拟使用PowerMock进行测试的专用方法?

如何模拟使用PowerMock进行测试的专用方法?,第1张

如何模拟使用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();    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5431995.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存