如何在对模拟静态方法的顺序调用中 return 多个答案

How can I return multiple answers in sequential calls to a mocked static method

我有一个函数 return 是 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 return 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 仍然 returned 两次。

我试过你的代码,它按你预期的那样工作。我创建了被测方法,如:

public String printHostname() throws Exception {
    return InetAddress.getLocalHost().getHostName();
}

和测试class:

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

}