首页 > 代码库 > PowerMock mock私有方法
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 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私有方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。