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

问题描述 投票:0回答:1

我有一个返回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仍然两次返回。

java junit mocking powermock
1个回答
0
投票

我尝试了你的代码,它正如你所期望的那样工作。我创建了测试方法,如:

Using Mockito with multiple calls to the same method with the same arguments

和测试类:

testHost
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.