验证是否使用 mockito 调用了三种方法之一 [英] Verify whether one of three methods is invoked with mockito

查看:55
本文介绍了验证是否使用 mockito 调用了三种方法之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三种方法:

public void method1(String str){
    ...
}

public void method1(String str, String str2, String str3){
    ...
}

public void method1(String str, String str2, Object[] objs, String str3){
    ...
}

如果调用了这些方法中的任何一个,我想检查 Mockito,所以我尝试使用 anyVararg Matcher:

I want to check in Mockito if any of these methods are invoked, so I've tried to use anyVararg Matcher:

verify(foo).method1(anyVararg());

但这不会编译错误类型中的方法 method1(String, String) 不适用于参数 (Object)"

but this doesn't compile "The method method1(String, String) in the type Errors is not applicable for the arguments (Object)"

我有两个问题:

  1. 我该如何解决这个问题?
  2. 有没有办法检查是否调用了两种方法中的任何一种?想象一下,我有另一个称为 method2 和 method3 的数学.我想检查是否调用了其中任何一个(但至少调用了一个).

谢谢.

推荐答案

如果调用任何方法,您可以使用 Answer 来增加计数器.

You could do this by using an Answer to increment a counter if any of the methods are called.

private Answer incrementCounter = new Answer() {
    public Object answer(InvocationOnMock invocation) throws Throwable {
        counter++;
        return null;
    }        
};

请注意,您需要存根所有方法.方法的唯一性基于其签名,而不仅仅是方法名称.两个同名的方法还是两种不同的方法.

Note that you need to stub all methods. A method's uniqueness is based on its signature and not just the method name. Two methods with the same name are still two different methods.

doAnswer(incrementCounter).when(mockObj.method1(anyString()));
doAnswer(incrementCounter).when(mockObj.method1(anyString(), anyString()));
doAnswer(incrementCounter).when(mockObj.method2(anyString()));

查看 doAnswer 的文档 这里.

这篇关于验证是否使用 mockito 调用了三种方法之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆