我正在使用Mockito用Java编写单元测试,并且我想验证某种方法是在对象上调用的最后一个方法。
我在被测试的代码中正在做这样的事情:
row.setSomething(value);
row.setSomethingElse(anotherValue);
row.editABunchMoreStuff();
row.saveToDatabase();
在我的模拟中,我不在乎编辑行中所有内容的顺序,但是非常重要的是,保存后不要尝试对其进行任何其他操作。有什么好方法吗?
请注意,我不是在寻找verifyNoMoreInteractions:它不会确认saveToDatabase是最后一次调用,并且如果我在未明确验证的行上调用任何内容,也会失败。我想说些类似的话:
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verifyTheLastThingCalledOn(row).saveToDatabase();
如果有帮助,我将从执行此操作的JMock测试切换到Mockito:
row.expects(once()).method("saveToDatabase").id("save");
row.expects(never()).method(ANYTHING).after("save");
我认为这需要更多的定制工作。
verify(row, new LastCall()).saveToDatabase();
然后
public class LastCall implements VerificationMode {
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
InvocationMatcher matcher = data.getWanted();
Invocation invocation = invocations.get(invocations.size() - 1);
if (!matcher.matches(invocation)) throw new MockitoException("...");
}
}
上一个答案:
你是对的。verifyNoMoreInteractions是您所需要的。
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verify(row).editABunchMoreStuff();
verify(row).saveToDatabase();
verifyNoMoreInteractions(row);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句