模拟功能

时间:2013-06-17 14:45:46

标签: java junit mockito

我对Mockito很新,如果我走在正确的轨道上,请告诉我。我正在尝试使用Mockito模拟方法功能。

sscce

public SUTclass {
    private final DependencyInjectedObj dep; // already successfully mocked
    private int statefulInteger;
    private int otherInteger;

    public int doSomething() {
        return otherInteger + dep.doMath(statefulInteger);
    }
}

目前,dep已被模拟......但dep.doMath始终返回0。在制作中,dep是有状态的 - 无法避免它。在生产中,不同的线程实时更新其状态。 dep.doMath根据州现状进行一些时髦的计算。您可以想象生产功能可能会查看温度计并使用它的温度执行某些操作,而doSomething会根据该温度提供实时状态。

在我的测试中,我希望dep.doMath具有此功能(这是单元测试的足够近似值):

public int doMath(int input) {
    return SOMECONSTANT * input;
}

我想我可以创建一个DependencyInjectedObj的Mock实现并使用它,但这似乎打败了使用Mockito和when语法的目的。我该怎么办?

1 个答案:

答案 0 :(得分:3)

在这种情况下,您想要的是doAnswer()。它允许您在调用模拟调用时执行任意代码:

doAnswer(new Answer<Integer>() {
  public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      int i = (int)args[0];
      return i * CONSTANT;
  }
}).when(dep.doMath(any(Integer.class));

但我确实认为doAnswer有点邪恶。通常thenReturn(CONSTANT)足以进行大多数单元测试。如果你要验证这个方法调用的结果,那么你正在测试错误的类 - 模拟你的依赖项是你不太关心它们的操作。