gpt4 book ai didi

easymock - 使用 PowerMock + EasyMock 模拟 final方法

转载 作者:行者123 更新时间:2023-12-04 00:46:18 25 4
gpt4 key购买 nike

我试图模拟对 final方法的调用 ResourceBundle.getString() .使用 PowerMock 1.4.12 和 EasyMock 3.1,调用不会被模拟;而是调用“真实”方法。

我的测试课:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ResourceBundle.class)
public class TestSuite {
@Before
public void setUp() throws Exception {
ResourceBundle resourceBundleMock = PowerMock.createNiceMock(ResourceBundle.class);
expect(resourceBundleMock.getString(BundleConstants.QUEUE)).andReturn("Queue");
PowerMock.replay(resourceBundleMock);

beanBeingTested.setMessages(resourceBundleMock);
}
...
}

BeanBeingTested 中的代码:
private ResourceBundle messages;
...
String label = messages.getString(BundleConstants.QUEUE);

错误信息:
java.util.MissingResourceException: Can't find resource for bundle $java.util.ResourceBundle$$EnhancerByCGLIB$$e4a02557, key Queue
at java.util.ResourceBundle.getObject(ResourceBundle.java:384)
at java.util.ResourceBundle.getString(ResourceBundle.java:344)
at com.yoyodyne.BeanBeingTested.setUpMenus(BeanBeingTested.java:87)

当我单步执行测试用例时,调试器显示 beanBeingTested.messages 的类型作为“类 java.util.ResourceBundle 的 EasyMock”,因此正确注入(inject)了模拟。 (此外,在设置期间调用 getString() 时调用 expect() 没有错误)。

使用普通模拟而不是漂亮模拟,我收到以下错误:
java.lang.AssertionError: 
Unexpected method call handleGetObject("Queue"):
getString("Queue"): expected: 1, actual: 0

知道我做错了什么吗?

谢谢。

最佳答案

您正在使用 EasyMock 创建一个实例。相反,在使用静态方法时,您必须模拟类(使用 PowerMock)。

它应该是这样工作的(不过用 EasyMock 3.0 和 PowerMock 1.5 测试过):

@RunWith(PowerMockRunner.class)
@PrepareForTest(ResourceBundle.class)
public class TestSuite {
@Before
public void setUp() throws Exception {
// mock the class for one method only
PowerMock.mockStaticNice(ResourceBundle.class, "getString");

// define mock-behaviour on the class, when calling the static method
expect(ResourceBundle.getString(BundleConstants.QUEUE)).andReturn("Queue");

// start the engine
PowerMock.replayAll();
}
}

(我知道这个问题已经存在几个月了,但它可能对其他人有所帮助)

关于easymock - 使用 PowerMock + EasyMock 模拟 final方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095568/

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