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
答案 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);
}