如何使用 JMockit 模拟 InetAddress.getLocalHost()

How to mock out InetAddress.getLocalHost() using JMockit

InetAddress 构造函数不可见,因为使用了工厂模式。

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

当我尝试使用工厂方法获取部分模拟实例时,出现错误:

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

您需要指定 InetAddress 应模拟任何子类:

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