繁体   English   中英

如何使用Mockito在整个系统中模拟类

[英]How to mock a class throughout the system using Mockito

我有一个这样的方法,我正在尝试使用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中可以这样做吗?

如果仅尝试测试getValue()方法的行为,则需要提供 (模拟)该方法所需的对象。

MiscUtil类需要一个Helper对象的实例。 因此,您需要通过MiscUtils的构造函数(或其他方式)传递此对象,因为它是此类的依赖项。

所以,一切,这是一个依赖 ,你不想考我要戏弄他,你会打电话只是要测试(真正的方法MiscUtil.getValue(MY_SPECIAL_int_PROPERTY)

您必须将模拟对象传递回,否则,Mockito将不知道其getProperties方法被调用。

您需要在MiscUtil类中添加一种将Helper注入的方法:

private Helper helper;
public Helper getHelper()
{
     return helper;
}
public void setHelper(Helper helper)
{
     this.helper = helper;
}

更新MiscUtil类以使用您注入的帮助器:

    public int getValue(String key){
    Properties properties = getHelper().getProperties() //This is the method 
                                                         //I need to mock
    return properties.get(key)
}

然后将此模拟对象放回MiscUtil中:

MiscUtil.setHelper(mock);

现在,Mockito模拟应该可以工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM