【问题标题】:Is there a `not` ArgumentMatcher for mockito stubbing是否有用于模拟存根的“非”ArgumentMatcher
【发布时间】:2020-02-19 15:13:58
【问题描述】:

我正在尝试验证是否使用long 调用了一个方法,该方法具有除给定值之外的任何值。

因此我想知道是否有适合我用例的ArgumentMatcher,例如:

verify(mObject).verifiedMethod(notEq(longValueThatShouldBeAvoided));

我找到了这个解决方法:

verify(mObject).method(longThat(arg -> arg != longValueThatShouldBeAvoided));

但我觉得很奇怪,这么简单的ArgumentMatcher 必须从头开始编写。


补充问题: 检查多个值以避免时如何进行?

同样,我找到了使用arg -> arg != val0 && arg != val1 lambda 作为ArgumentsMatcher.longThat 方法的参数来实现此目的的解决方法。

【问题讨论】:

    标签: java mockito hamcrest


    【解决方案1】:

    尝试:

    import static org.mockito.AdditionalMatchers.not; 
    import static org.mockito.ArgumentMatchers.eq;
    
    verify(mObject).verifiedMethod(not(eq(longValueThatShouldBeAvoided)));
    

    【讨论】:

    • 您介意指定您建议的not 方法吗?我的意思是,它是在哪个包中声明的。
    • @EnzoMolion import static org.mockito.AdditionalMatchers.not; import static org.mockito.ArgumentMatchers.eq;
    • 成功了,谢谢!我以为我试过了,但我的 IDE 实际上是在导入 org.hamcrest.Matcher's not...
    【解决方案2】:

    我认为您可能正在寻找 AdditionalMatchers 中的“非”匹配器。

    但是,我认为this other question 对此进行了更广泛的处理。

    【讨论】:

    • 虽然这个问题实际上完美地回答了我的问题,而其他几个问题也确实如此,但我在研究过程中没有找到它们,对此感到抱歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多