我有一个返回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
。
答案 0 :(得分:0)
我尝试了您的代码,它按预期工作。我创建了如下测试方法:
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());
}
}