gpt4 book ai didi

java - JMockit - 模拟 System.getProperties() 时为 "Missing invocation to mocked type"

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:40 25 4
gpt4 key购买 nike

诚然,我是 JMockit 的新手,但出于某种原因,我在模拟 System.getProperties() 时遇到了麻烦。感谢以下帖子的帮助:

https://stackoverflow.com/questions/25664270/how-can-i-partially-mock-the-system-class-with-jmockit-1-8?lq=1

我可以使用 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());
}

我得到以下指向“返回”方法的异常:

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 block 中(首先是 getProperty()),那么我看不到异常,但 System.getProperties() 返回真实的系统属性,而不是模拟的;尽管 getProperty(propertyName) 返回模拟值。我发现这种行为非常古怪。

我从这篇文章中看到某些方法不能被模拟,但 System.getProperties() 不在该列表中:

JMockit NullPointerException on Exceptions block?

我还发现 2-3 年前使用 JMockit 的许多 SO 解决方案现在完全不可编译,所以显然情况发生了很大变化。

最佳答案

System.getProperties() 确实是 JMockit 1.12 中被排除在模拟之外的方法之一。当发现新的有问题的 JRE 方法时,这些被排除的方法的确切集合可能会在较新的版本中发生变化。

虽然没有必要模拟 System.getProperty(...)System.getProperties()System 类提供了可以替代使用的 setPropertysetProperties 方法。

关于java - JMockit - 模拟 System.getProperties() 时为 "Missing invocation to mocked type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com