【问题标题】:How to mock a class throughout the system using Mockito如何使用 Mockito 在整个系统中模拟一个类
【发布时间】: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


【解决方案1】:

你必须把 mock 对象传回去,否则,Mockito 不会知道它的 getProperties 方法被调用了。

你需要在你的 MiscUtil 类中添加一个注入 Helper 的方法:

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

更新 MiscUtil 类以使用您注入的 Helper:

    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 模拟应该可以工作了

【讨论】:

  • Mockito 的功能比 JMockit 少很多。 Mockito 可以用来测试静态方法吗?如果有办法做到这一点,我可以解决这个问题。
  • 不,你不能。这实际上是有道理的。模拟对象应该作为依赖注入到类中。
  • @SalilSurendran 是的,您可以在使用 Mockito 时做到这一点,前提是您还使用 PowerMockito(支持 Mockito 的 PowerMock 库的一部分)来进行诸如模拟 @987654324 之类的事情@ 和 static 方法、构造函数和 new-ed 对象。
【解决方案2】:

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

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

因此,如果我嘲笑它是 依赖项 并且您 不想 想要测试的所有内容,您将只调用您想要测试的真实方法(@ 987654324@).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2018-02-15
    • 2013-05-07
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多