我有一个返回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();
我在这里尝试使用qazxsw poi解决方案:qazxsw poi
但是没有效果,因为doAnswer
仍然两次返回。
我尝试了你的代码,它正如你所期望的那样工作。我创建了测试方法,如:
Using Mockito with multiple calls to the same method with the same arguments
和测试类:
testHost