Use Mockito to verify that nothing is called after a method(使用 Mockito 验证方法后没有调用任何内容)
问题描述
我正在使用 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 验证方法后没有调用任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Mockito 验证方法后没有调用任何内容
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01