我正在使用 Mockito 编写 Java 单元测试,我想验证某个方法是否是对象上调用的最后一个.
I'm using Mockito to write a unit test in Java, and I'd like to verify that a certain method is the last one called on an object.
我在被测代码中做了这样的事情:
I'm doing something like this in the code under test:
row.setSomething(value);
row.setSomethingElse(anotherValue);
row.editABunchMoreStuff();
row.saveToDatabase();
在我的模拟中,我不关心编辑行中所有内容的顺序,但重要的是我不在保存后尝试对其执行更多操作它.有没有好的方法来做到这一点?
In my mock, I don't care about the order in which I edit everything on the row, but it's very important that I not try to do anything more to it after I've saved it. Is there a good way to do this?
请注意,我不是在寻找 verifyNoMoreInteractions:它不会确认 saveToDatabase 是最后调用的东西,如果我调用行上没有明确验证的任何内容,它也会失败.我希望能够这样说:
Note that I'm not looking for verifyNoMoreInteractions: it doesn't confirm that saveToDatabase is the last thing called, and it also fails if I call anything on the row that I don't explicitly verify. I'd like to be able to say something like:
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verifyTheLastThingCalledOn(row).saveToDatabase();
如果有帮助,我将从执行此操作的 JMock 测试切换到 Mockito:
If it helps, I'm switching to Mockito from a JMock test that did this:
row.expects(once()).method("saveToDatabase").id("save");
row.expects(never()).method(ANYTHING).after("save");
我认为这需要更多的自定义工作.
I think it requires more custom work.
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 是您所需要的.
You are right. verifyNoMoreInteractions is what you need.
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verify(row).editABunchMoreStuff();
verify(row).saveToDatabase();
verifyNoMoreInteractions(row);
这篇关于使用 Mockito 验证方法后没有调用任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!