java - 如何在对模拟静态方法的顺序调用中返回多个答案
问题描述
我有一个返回值的函数 java.net.InetAddress.getLocalHost().getHostName()
我已经为我的函数编写了一个测试,如下所示:
@PrepareForTest({InetAddress.class, ClassUnderTest.class})
@Test
public void testFunc() throws Exception, UnknownHostException {
final ClassUnderTest classUnderTest = new ClassUnderTest();
PowerMockito.mockStatic(InetAddress.class);
final InetAddress inetAddress = PowerMockito.mock(InetAddress.class);
PowerMockito.doReturn("testHost", "anotherHost").when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();
PowerMockito.doReturn(inetAddress).when(InetAddress.class);
InetAddress.getLocalHost();
Assert.assertEquals("testHost", classUnderTest.printHostname());
Assert.assertEquals("anotherHost", classUnderTest.printHostname());
}
printHostName
简直就是return java.net.InetAddress.getLocalHost().getHostName();
我将如何调用getHostName
返回anotherHost
第二个断言?
我试过做:
((PowerMockitoStubber)PowerMockito.doReturn("testHost", "anotherHost"))
.when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();
PowerMockito.doReturn("testHost", "anotherHost")
.when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();
我在这里尝试使用doAnswer
解决方案:Using Mockito with multiple calls to the same method with the same arguments
但没有效果,因为testHost
两次仍然返回。
解决方案
我尝试了您的代码,它按您的预期工作。我创建了被测方法,例如:
public String printHostname() throws Exception {
return InetAddress.getLocalHost().getHostName();
}
和测试类:
@RunWith(PowerMockRunner.class)
public class ClassUnderTestTest {
@PrepareForTest({InetAddress.class, ClassUnderTest.class})
@Test
public void testFunc() throws Exception {
final ClassUnderTest classUnderTest = new ClassUnderTest();
PowerMockito.mockStatic(InetAddress.class);
final InetAddress inetAddress = PowerMockito.mock(InetAddress.class);
PowerMockito.doReturn("testHost", "anotherHost")
.when(inetAddress, PowerMockito.method(InetAddress.class, "getHostName"))
.withNoArguments();
PowerMockito.doReturn(inetAddress).when(InetAddress.class);
InetAddress.getLocalHost();
Assert.assertEquals("testHost", classUnderTest.printHostname());
Assert.assertEquals("anotherHost", classUnderTest.printHostname());
}
}
推荐阅读
- visual-studio - ASP.NET MVC 网站视图模型在发布后未更新,但在发布中运行良好
- c# - 在右对齐的 PdfPCell 中查找文本的起始 x 坐标
- reactjs - ReactDOM.render 在 getUserConfirmation 中不起作用
- php - 表单提交后重新加载网页,隐藏 iframe
- python - 如何限制使用pynput按下的键
- c# - C# 在 for 循环期间检查取消令牌
- javascript - Discord.js - UnhandledPromiseRejectionWarning:RangeError [MESSAGE_NONCE_TYPE]:消息随机数必须适合无符号 64 位整数
- ios - 上传图片到服务器时出现绿线
- java - 需要有关 java 泛型问题的帮助
- python - Python RE:如何将文字分割为 0 次或多次 *