【发布时间】:2014-08-16 17:09:38
【问题描述】:
我有一个类似的方法,我正在尝试使用 Mockito 进行测试:
public class MiscUtil{
public int getValue(String key){
Properties properties = new Helper().getProperties() //This is the method
//I need to mock
return properties.get(key)
}
这是测试类:
public class MiscUtilTest{
public void testGetBooleanValue() {
Properties properties = new Properties();
properties.setProperty(MY_SPECIAL_INT_PROPERTY, 10);
// Mock Helper
Helper mock = Mockito.mock(Helper.class);
// mock the method getProperties()
Mockito.when(mock.getProperties()).thenReturn(properties);
// Assert that the getValue() method
Assert.assertEquals(10,MiscUtil.getValue(MY_SPECIAL_int_PROPERTY));
但是,该方法不会被嘲笑。我是否必须将实际的模拟实例传递给 MiscUtil 类才能使模拟生效? MiscUtil 类不允许我将 Helper 对象传递给它。在 JMockit 中模拟任何类的特定方法非常容易,即使上层类可能无法访问它。在 Mockito 中可以做到这一点吗?
【问题讨论】:
-
Do I have to pass the actual mocked instance into the MiscUtil class in order for mocking to take effect?是的。这是一种解决方案。 -
您可能会从my article on the Mockito wiki获得一些见解
标签: java unit-testing mocking mockito