zoukankan      html  css  js  c++  java
  • PowerMock mock私有方法

    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/

  • 相关阅读:
    bean扫描的问题
    软件测试综合实训提问环节
    cephfs
    Django ORM数据增删改查接口
    ceph使用问题积累
    ceph删除pool
    Windows容器使用阿里云NAS SMB文件系统做持久化存储目录
    ceph安装( nautilus 版本 )
    K8S使用cephcsi持久化存储之CephFS
    服务器监控jmeter之 jp@gc PerfMon Metrics Collector
  • 原文地址:https://www.cnblogs.com/softidea/p/4204376.html
Copyright © 2011-2022 走看看