博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PowerMock mock私有方法
阅读量:7230 次
发布时间:2019-06-29

本文共 1453 字,大约阅读时间需要 4 分钟。

 

import java.util.Random;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;    }}

PowerMock:

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://codego.net/368377/

 

转载地址:http://ywpfm.baihongyu.com/

你可能感兴趣的文章
包含目录、库目录、附加包含目录、附加库目录、附加依赖项
查看>>
Apache+SVN+Review Board代码审核服务器搭建流程
查看>>
esproc vs python 5
查看>>
分布式系统下的哈希一致性算法设计
查看>>
NFS存储服务部署(上)
查看>>
dd测试硬盘性能
查看>>
DNS设置
查看>>
linux的SELinux的设置及防火墙服的设置
查看>>
awk的数组的应用
查看>>
java----调用windows的DOS命令并回显/启动和关闭appium
查看>>
linux下配置ip地址四种方法(图文方法)转载
查看>>
Google Chrome 总提示flash插件过期,用命令行模式解决
查看>>
定位与坐标系算法
查看>>
化学绘图软件ChemDraw真的什么都能干!
查看>>
Python开发注意事项
查看>>
FUCKED-BUG之临时对象的生死
查看>>
【转】HTML5第一人称射击游戏发布
查看>>
centos配置私钥登录
查看>>
web本地存储-WebSQL
查看>>
ORACLE11g:No Dialect mapping for JDBC type: -9解决方案
查看>>