【问题标题】:Mockito: Match any String except one [duplicate]Mockito:匹配除一个之外的任何字符串[重复]
【发布时间】:2023-03-13 21:55:02
【问题描述】:

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

我曾尝试使用一些 hamcrest 匹配器来否定和组合其他匹配器,但 hamcrest 匹配器都返回类型为 Matcher<T> 的值,这与 Mockito 匹配器效果不佳。

【问题讨论】:

标签: java string junit mockito matcher


【解决方案1】:

只需指出Mockito 还可以使用AdditionalMatchersArgumentMatchers

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

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

根据其文档:

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

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

在这个SO question有更多信息

希望对你有帮助

【讨论】:

    【解决方案2】:

    我使用的解决方案:

    import static org.hamcrest.CoreMatchers.not;
    import static org.mockito.ArgumentMatchers.argThat;
    
    // ...
    
    argThat(not("ExceptionString"))
    

    版本

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 2018-07-28
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      相关资源
      最近更新 更多