我正在单元测试的类需要依赖项并调用该依赖项的函数。该函数将一个复杂对象作为其参数并产生一个结果。现在,我想模拟依赖项并让它根据传入的参数返回一些内容。下面给出了一个简化的工作版本。
我可以在 when
方法中使用 Java 8 lambda 表达式来消除 ArgHasNext
类吗?类似于下面的注释代码(无法编译)。
class ArgHasNext implements ArgumentMatcher<Arg> {
public boolean matches(Arg arg) {
return arg.hasNext();
}
@Override
public boolean matches(Object o) {
return matches((Arg)o);
}
}
@RunWith(MockitoJUnitRunner.class)
public class ArgumentMatcherTest {
@Mock
private Dependency dep = mock(Dependency.class);
@Test
public void test() {
when(dep.func(argThat(new ArgHasNext()))).thenReturn(true);
// when(dep.func(argThat((Arg a) -> a.hasNext()))).thenReturn(true);
// when(dep.func(argThat((Arg a) -> !a.hasNext()))).thenReturn(false);
Sut sut = new Sut(dep);
assertEquals(sut.method(new Arg(true)), "True");
assertEquals(sut.method(new Arg(false)), "False");
}
}
class Arg {
private boolean hasNext;
public Arg(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean hasNext() {
return this.hasNext;
}
}
class Sut {
private Dependency dep;
public Sut(Dependency dep) {
this.dep = dep;
}
public String method(Arg arg) {
if (dep.func(arg)) {
return "True";
}
else {
return "False";
}
}
}
class Dependency {
public boolean func(Arg arg) {
if (arg.hasNext()) {
return true;
}
return false;
}
}
我正在使用 Mockito-core 版本 2.0.54-beta。
编辑
好吧,也许我过度简化了这个例子。在实际情况下,依赖项 func
方法返回分页查询结果,这些结果在测试方法返回之前在 SUT
中处理。根据 Arg
,我希望依赖项 func
在第一次调用时返回第 1 页结果,第二次调用时返回第 2 页结果。只有当我可以让模拟根据传递给函数调用的参数返回不同的值时,我才能这样做。这可能在 Mockito 中使用 lambda 吗?
最佳答案
Now, I would like to mock the dependency and have it return something based on the argument passed in.
你一开始就不应该这样做。 无论如何让你的模拟返回明确定义的常量值。
原因是您应该使测试代码尽可能简单,以降低因测试代码错误而导致测试失败的风险。
您的问题的解决方案可能是 mockitos Answer
接口(interface):
doAnswer(new Answer<YourReturnType>(){
public YourReturnType answer(InvocationOnMock invocation) {
YourParameterType parameter = (YourParameterType)invocation.getArguments()[0];
// calculate your return value
return yourCalculatedReturnValue;
}
}).when(yourMock).theMethod(any(YourParameterType.class));
To be clear, my mock is returning a constant value. The mock is called multiple times and I want it to return a different value the second time. – MvdD
你应该在你的问题中写下这个。解决方案听起来很简单:
doReturn(VALUE_FOR_FIRST_CALL).
thenReturn(VALUE_FOR_SECOND_CALL).
thenReturn(VALUE_FOR_ANY_FURTHER_CALL).
when(mock).theMethod();
或者如果你更喜欢少说话:
doReturn(VALUE_FOR_FIRST_CALL, VALUE_FOR_SECOND_CALL, VALUE_FOR_ANY_FURTHER_CALL).
when(mock).theMethod();
关于java - 使用 Java8 lambda 在模拟类上进行参数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45993599/