java Mockito:匹配除一个之外的任何字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30107476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:29:45  来源:igfitidea点击:

Mockito: Match any String except one

javastringjunitmockitomatcher

提问by Stephan

How can I write a matcher using Mockito that matches any string except a specific one?

如何使用 Mockito 编写匹配除特定字符串以外的任何字符串的匹配器?

I have tried using some hamcrest matchers to negate and combine other matchers, but the hamcrest matchers all return values of type Matcher<T>which dont work very well with Mockito matchers.

我曾尝试使用一些 hamcrest 匹配器来否定和组合其他匹配器,但 hamcrest 匹配器都返回Matcher<T>与 Mockito 匹配器不能很好地工作的类型值。

回答by Stephan

The solution I used:

我使用的解决方案:

argThat(not("ExceptionString"))

Where argThatis a Mockito matcher,
and notis a Hamcrest Matcher

哪里argThat是匹配的Mockito,
而且not是一个Hamcrest匹配器

回答by troig

Just point that with Mockitoyou can also use AdditionalMatchersand ArgumentMatchers

只需指出Mockito您还可以使用AdditionalMatchersArgumentMatchers

import static org.mockito.AdditionalMatchers.not;
import static org.mockito.ArgumentMatchers.eq;

//anything but not "ejb"    
mock.someMethod(not(eq("ejb")));

According its documentation:

根据其文档:

Example of using logical and(), not(), or() matchers:

//anything but not "ejb"
mock.someMethod(not(eq("ejb")));

使用逻辑 and()、not() 或 () 匹配器的示例:

//除了“ejb”
之外的任何东西mock.someMethod(not(eq("ejb")));

There is more info in this other SO question

在这个其他SO 问题中有更多信息

Hope it helps

希望能帮助到你