码迷,mamicode.com
首页 > 其他好文 > 详细

PowerMock mock私有方法

时间:2015-01-05 20:14:12      阅读:556      评论:0      收藏:0      [点我收藏+]

标签:

 

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 java.lang.reflect.Method;

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/

 

PowerMock mock私有方法

标签:

原文地址:http://www.cnblogs.com/softidea/p/4204376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!