0

The InetAddress constructor is not visible because the factory pattern is used.

final InetAddress anyInstance = InetAddress.getLocalHost();
    new NonStrictExpectations(InetAddress.class) {
      {
        anyInstance.getHostAddress();
        result = "192.168.0.101";
      }
    };

When I try to use the factory method to get an instance for partial mocking I get the error:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
johnjamesmiller
  • 720
  • 5
  • 14

1 Answers1

1

You need to specify that InetAddress and any subclasses should be mocked:

@Test
public void mockAnyInetAddress(@Capturing final InetAddress anyInstance)
    throws Exception
{
    new Expectations() {{
        anyInstance.getHostAddress(); result = "192.168.0.101";
    }};

    String localHostAddress = InetAddress.getLocalHost().getHostAddress();

    assertEquals("192.168.0.101", localHostAddress);
}
Rogério
  • 16,171
  • 2
  • 50
  • 63
  • It looks like it is not correctly partially mocking when combined with Capturing. When I run your exact code I get: mockit.internal.UnexpectedInvocation: Unexpected invocation of: java.net.InetAddress#getLocalHost() If I set it as a NonStrictExpectations I get a null pointer exception because getLocalHost returns null. I am using JMockit 1.8 which looks to be a year old. I will see if a newer version fixes it – johnjamesmiller May 13 '15 at 18:25
  • looks like it was an issue with 1.8. it works fine in 1.17. not sure which version it was fixed in. Thanks for your help! – johnjamesmiller May 13 '15 at 18:49