Mockito: How to verify a method was called only once with exact parameters ignoring calls to other methods?(Mockito:如何验证一个方法只被调用一次,使用精确的参数忽略对其他方法的调用?)
问题描述
在 Java 中使用 Mockito 如何验证一个方法只被调用了一次,而忽略了对其他方法的调用?
Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?
示例代码:
public class MockitoTest {
interface Foo {
void add(String str);
void clear();
}
@Test
public void testAddWasCalledOnceWith1IgnoringAllOtherInvocations() throws Exception {
// given
Foo foo = Mockito.mock(Foo.class);
// when
foo.add("1"); // call to verify
foo.add("2"); // !!! don't allow any other calls to add()
foo.clear(); // calls to other methods should be ignored
// then
Mockito.verify(foo, Mockito.times(1)).add("1");
// TODO: don't allow all other invocations with add()
// but ignore all other calls (i.e. the call to clear())
}
}
TODO: 不允许使用 add() 部分的所有其他调用中应该做什么?
What should be done in the TODO: don't allow all other invocations with add() section?
已经尝试失败:
verifyNoMoreInteractions(foo);
不.它不允许调用其他方法,例如 clear().
Nope. It does not allow calls to other methods like clear().
verify(foo, times(0)).add(any());
不.它没有考虑到我们允许一次调用 add("1").
Nope. It does not take into account that we allow one call to add("1").
推荐答案
Mockito.verify(foo, Mockito.times(1)).add("1");
Mockito.verify(foo, Mockito.times(1)).add(Mockito.anyString());
第一个 verify 检查预期的参数化调用,第二个 verify 检查是否只有一次对 add 的调用.
The first verify checks the expected parametrized call and the second verify checks that there was only one call to add at all.
这篇关于Mockito:如何验证一个方法只被调用一次,使用精确的参数忽略对其他方法的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mockito:如何验证一个方法只被调用一次,使用精确
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
