Mockito ArgumentMatchers doesNotMatch?

mik*_*ent 3 java regex matcher mockito

ArgumentMatchers.matches( String regex )存在...并且可以设计与给定的匹配的正则表达式String。但这绝非微不足道(SO 中的几个线程)。

我是否认为要求 Mockito 设计师去掉繁重的工作并将其添加为一项功能可能是一个好主意,这是错误的(或者是错误的)吗?看起来,在嘲笑等背景下,这是一个远非特殊的用例......

PS 另外,我不清楚你如何说“这可能是我们正在匹配的多行字符串,不用担心它”......拥有一个而不是一个简单的ArgumentMatchers.matches不是更好吗??PatternString

之后

Mockito 总部(Github 上)的功能请求“增强”。“bric3”表示应该使用 Jeff Bowman 的技术来表示“不匹配”。但她/他似乎认为这个Pattern想法值得思考。

回复not():Mockito自己的文档说“非常明智地使用额外的匹配器,因为它们可能会影响测试的可读性。建议使用 Matchers 中的匹配器并保持存根和验证简单。”

另外我发现我必须“可能欺骗”我自己的问题:如何编写一个不等于某些内容的匹配器。事后搜索总是更容易......!

再后来

非常感谢 Brice 这么快就添加了这个。更新了我的 gradle.build 并...从 Maven Central 下载了新的 4.1 核心并立即可供使用。

Jef*_*ica 6

无需请求:您可以使用AdditionalMatchers.not编写您想要的内容。

when(yourComponent.acceptString(not(matches("foo|ba[rz]"))))
    .thenThrow(new IllegalArgumentException());
Run Code Online (Sandbox Code Playgroud)

如果您想匹配模式,您可能需要编写自己的ArgumentMatcher子类,但这很容易:

public class MatchesPattern implements ArgumentMatcher<String> {
  private final Pattern pattern;
  public MatchesPattern(Pattern pattern) { this.pattern = pattern; }

  @Override public boolean matches(String string) {
    return pattern.matcher(string).matches();
  }

  @Override public String toString() {
    return "[string matching /" + pattern.toString() + "/]";
  }

  /** Optional. */
  public static MatchesPattern matchesPattern(Pattern pattern) {
    return new MatchesPattern(pattern);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用该类:

when(yourComponent.acceptString(not(argThat(new MatchesPattern(yourPattern)))
    .thenThrow(new IllegalArgumentException());

// or with the static factory method:
when(yourComponent.acceptString(not(argThat(matchesPattern(yourPattern)))
    .thenThrow(new IllegalArgumentException());
Run Code Online (Sandbox Code Playgroud)