栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456477.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号