简体   繁体   English

Mockito ArgumentCaptor根据匹配器捕获

[英]Mockito ArgumentCaptor Capture Conditional on Matcher

In mockito we can capture arguments for a method that might be called many times like so: 在mockito中,我们可以捕获可能多次调用的方法的参数,如下所示:

verify(mocked, atLeastOnce())
    .myMethod(myCaptor.capture());

Then 然后

myCaptor.getAllValues()

However then I would need to sift through all the captured values to find the one I am interested in for verification. 但是,然后我将需要筛选所有捕获的值,以找到我感兴趣的值进行验证。

What I would like to do is something like this: 我想做的是这样的:

private class IsMySpecialArg extends ArgumentMatcher<Object> {
  public boolean matches(Object other) {
    // Matching condition
  }
}

... ...

verify(mocked, atLeastOnce())
        .myMethod(myCaptor.capture(argThat(new IsMySpecialArg()));

So that I can simply call myCaptor.getValue() and be assured it is referring to the argument I was actually interested in capturing. 这样我就可以简单地调用myCaptor.getValue()并确保它引用的是我实际上有兴趣捕获的参数。 What is the best way to accomplish this is mockito , is it supported, or is there something fundamentally wrong with my testing strategy? 什么是实现这一目标的最好方法mockito ,是它支持的,或者是有什么根本性的错误与我的测试策略?

I use ArgumentMatchers pretty frequently when writing tests. 编写测试时,我经常使用ArgumentMatchers。 Here's an example of what you can do when verifying the arguments that are passed to your mock objects: 这是验证传递给模拟对象的参数时可以执行的示例:

private static class ExpectationArgumentMatcher extends ArgumentMatcher<String> {

    private final List<String> expectedArguments;

    public ExpectationArgumentMatcher(List<String> expectedArguments) {
        this.expectedArguments = expectedArguments;
    }

    public ExpectationArgumentMatcher() {
        this(new ArrayList<javax.swing.Action>());
    }


    @Override
    public boolean matches(Object argument) {
        if (argument instanceof String) {
            String actualArgument = (String) argument;
            return expectedArguments.contains(actualArgument);
        }
        return false;
    }
}

Obviously, you're expected arguments could just be a string, or something more sophisticated, but you're basically checking that your mock was called upon with an argument that matches your expected argument(s). 显然,您期望参数可以是字符串,也可以是更复杂的东西,但是您基本上是在检查是否使用与期望参数匹配的参数调用了模拟程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM