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

时间:2015-05-11 22:37:16

标签: 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

1 个答案:

答案 0 :(得分:1)

您需要指定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);
}