【发布时间】:2014-11-04 17:25:27
【问题描述】:
诚然,我是 JMockit 的新手,但由于某种原因,我在模拟 System.getProperties() 时遇到了麻烦。感谢以下帖子的帮助:
我可以使用 JMockit 1.12 成功模拟 System.getProperty():
@Test
public void testAddSystemProperty_String() {
final String propertyName = "foo";
final String propertyValue = "bar";
new Expectations(System.class) {{
System.getProperty(propertyName);
returns(propertyValue);
}};
assertEquals(propertyValue, System.getProperty(propertyName));
}
但是用于模拟 getProperties() barfs 的异常相似的代码:
@Test
public void testAddSystemProperty_String() {
final String propertyName = "foo";
final String propertyValue = "bar";
final Properties properties = new Properties();
properties.setProperty(propertyName, propertyValue);
new Expectations(System.class) {{
System.getProperties();
returns(properties);
}};
assertEquals(1, System.getProperties().size());
}
我得到以下指向“returns”方法的异常:
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
另外,我如何同时模拟这两种方法?如果我将它们放在同一个 Expectations 块中(首先使用 getProperty() ),那么我看不到异常,但 System.getProperties() 返回真实的系统属性,而不是模拟的;虽然 getProperty(propertyName) 返回模拟值。我发现这种行为完全不可靠。
我从这篇文章中看到某些方法不能被模拟,但 System.getProperties() 不在该列表中:
JMockit NullPointerException on Exceptions block?
我还发现,2-3 年前与 JMockit 一起使用的许多 SO 解决方案现在完全不可编译,因此显然情况发生了很大变化。
【问题讨论】:
标签: java unit-testing jmockit