1

I have a function that returns the value of java.net.InetAddress.getLocalHost().getHostName()

I have written a test for my function like so:

@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 is simply return java.net.InetAddress.getLocalHost().getHostName();

How would I have the call to getHostName return anotherHost for the second assert?

I've tried doing:

((PowerMockitoStubber)PowerMockito.doReturn("testHost", "anotherHost"))
.when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();
PowerMockito.doReturn("testHost", "anotherHost")
.when(inetAddress, method(InetAddress.class, "getHostName")).withNoArguments();

and ive tried using the doAnswer solution here: Using Mockito with multiple calls to the same method with the same arguments

But to no effect, as testHost is still returned both times.

John Bergqvist
  • 852
  • 13
  • 38

1 Answers1

0

I tried your code and it is working as you expect. I created the method under test like:

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

And the test 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());
    }

}