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

编程入门 行业动态 更新时间:2024-10-27 00:24:47
本文介绍了如何模拟使用 PowerMock 进行测试的私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个类,我想用一个调用私有方法的公共方法来测试它.我想假设私有方法正常工作.例如,我想要类似 doReturn....when... 的东西.我发现有使用 PowerMock 的可能解决方案,但该解决方案对我不起作用.如何做到?有人遇到过这个问题吗?

I have a class which I would like to test with a public method that calls private one. I'd like to assume that private method works correctly. For example, I'd like something like doReturn....when.... I found that there is possible solution using PowerMock, but this solution doesn't work for me. How It can be done? Did anybody have this problem?

推荐答案

我看不出这里有什么问题.通过使用 Mockito API 的以下代码,我设法做到了:

I don't see a problem here. With the following code using the Mockito API, I managed to do just that :

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 测试:

And here's the JUnit test :

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(); } }

更多推荐

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

本文发布于:2023-10-31 03:55:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进行测试   方法   PowerMock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!