我有一个返回值的函数 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两次仍然返回。
三国纷争
相关分类