我想使用Mockito验证字符串参数是否满足两个条件:
verify(mockClass).doSomething(Matchers.startsWith("prefix"));
verify(mockClass).doSomething(Matchers.endsWith("suffix"));
如何将这两者合并为一个陈述?
答案 0 :(得分:25)
使用org.mockito.AdditionalMatchers
:
import static org.mockito.AdditionalMatchers.and;
verify(mockClass).doSomething(
and(Matchers.startsWith("prefix"),
Matchers.endsWith("suffix"));
还有org.mockito.AdditionalMatchers.or
和org.mockito.AdditionalMatchers.not
。
答案 1 :(得分:1)
之前的评论已经提到and
只需要两个参数,并且具有三个或更多变量的变体将是有利的。以下代码以递归方式解决此问题,允许在varargs中指定多个匹配器:
public static String conjunction(String... matchers) {
if (matchers.length < 2) {
throw new IllegalArgumentException("matchers.length must be >= 2");
} else if (matchers.length == 2) {
return and(matchers[0], matchers[1]);
} else {
final String[] tail = new String[matchers.length - 1];
System.arraycopy(matchers, 1, tail, 0, tail.length);
return and(matchers[0], conjunction(tail));
}
}
假设以下导入:
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Mockito.*;