如何将多个Mockito匹配器与逻辑“和”/“或”结合起来?

时间:2014-03-20 08:37:18

标签: mockito

我想使用Mockito验证字符串参数是否满足两个条件:

verify(mockClass).doSomething(Matchers.startsWith("prefix"));
verify(mockClass).doSomething(Matchers.endsWith("suffix"));

如何将这两者合并为一个陈述?

2 个答案:

答案 0 :(得分:25)

使用org.mockito.AdditionalMatchers

可以实现
import static org.mockito.AdditionalMatchers.and;

verify(mockClass).doSomething(
         and(Matchers.startsWith("prefix"), 
             Matchers.endsWith("suffix"));

还有org.mockito.AdditionalMatchers.ororg.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.*;