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

时间:2019-04-16 09:39:38

标签: java junit mocking powermock

我有一个返回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

1 个答案:

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

}
相关问题