【问题标题】:Stub a method basing on arguments存根基于参数的方法
【发布时间】:2016-06-09 05:12:35
【问题描述】:
class ArgumentClass{
   int var;
}

class ClassMocked{
   int aMothod(ArgumentClass argumentClass){
      return anInt;
   }
}

class MyTest{
   Mock and Stub here
}

在 MyTest 中,我想对 aMothod 进行存根,以便它根据 ArgumentClass.var 的值返回值。我必须一口气完成。 换句话说,我有一个测试用例,其中应用程序代码调用了 3 次 moehod,并且基于参数对象中的变量,我需要不同的返回值。我需要相应地存根。如果有办法请告诉我。

【问题讨论】:

  • 您应该提供更多关于您想要的测试和模拟方法的预期结果的信息。例如,您可以致电when(mock.aMethod(any())).thenReturn(1,2,3),但我对您的方案了解得不够多,无法知道这是否是您所需要的。

标签: mockito stub


【解决方案1】:

如果我理解正确,您可以使用 mockito 以两种不同的方式进行操作。如果您将 ClassMocked 声明为模拟,您应该可以这样说:

when(mock.aMothod(eq(specificArgument))).thenReturn(1);
when(mock.aMothod(eq(anotherSpecificArgument))).thenReturn(2);

如果你想这样做,不管传递的参数是什么,你都希望根据方法的调用次数返回值,你可以说:

when(mock.aMothod(any())).thenReturn(1, 2);

这表示当调用 aMothod 而不管传递的参数 (any()) 时,它将在第一次调用时返回 1,在第二次调用时将返回 2。

【讨论】:

  • 第一个解决方案取决于 ArgumentClass 具有覆盖的 equals 方法。另一种解决方案是简单地为它实现一个自定义Matcher
【解决方案2】:

虽然您可以按正确的顺序设置模拟返回值,如karruma's answer,但您也可以使用Answer 来计算模拟值:

when(mock.aMothod(any())).thenAnswer(new Answer<Integer>() {
  @Override public Integer answer(InvocationOnMock invocation) {
    ArgumentClass argument = invocation.getArguments()[0];
    return calculationBasedOn(argument);
  }
});

或者在 Java 8 和 Mockito 2 beta 中(未经测试,可能需要装箱/拆箱):

when(mock.aMothod(any())).thenAnswer(invocation ->
    calculatebasedOn(invocation.getArgumentAt(0, ArgumentClass.class)));

虽然我在顶部示例中有一个匿名内部类,但您自然可以创建一个命名的 Answer 子类并在您的应用程序中重用它。

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2010-12-15
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多