Mockito 匹配任何类参数 [英] Mockito match any class argument

查看:48
本文介绍了Mockito 匹配任何类参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法匹配以下示例例程的任何类参数?

Is there a way to match any class argument of the below sample routine?

class A {
     public B method(Class<? extends A> a) {}
}

我怎样才能总是返回一个new B(),而不管哪个类被传入method?以下尝试仅适用于 A 匹配的特定情况.

How can I always return a new B() regardless of which class is passed into method? The following attempt only works for the specific case where A is matched.

A a = new A();
B b = new B();
when(a.method(eq(A.class))).thenReturn(b);

<小时>

编辑:一种解决方案是

(Class<?>) any(Class.class)

推荐答案

另外两种方法(见我对@Tomasz Nurkiewicz 上一个回答的评论):

Two more ways to do it (see my comment on the previous answer by @Tomasz Nurkiewicz):

第一个依赖于编译器根本不会让你传入错误类型的东西的事实:

The first relies on the fact that the compiler simply won't let you pass in something of the wrong type:

when(a.method(any(Class.class))).thenReturn(b);

您丢失了确切的类型(Class),但它可能会按您的需要工作.

You lose the exact typing (the Class<? extends A>) but it probably works as you need it to.

第二个涉及更多,但如果您真的想确保 method() 的参数是 AA 的子类:

The second is a lot more involved but is arguably a better solution if you really want to be sure that the argument to method() is an A or a subclass of A:

when(a.method(Matchers.argThat(new ClassOrSubclassMatcher<A>(A.class)))).thenReturn(b);

其中 ClassOrSubclassMatcher 是一个 org.hamcrest.BaseMatcher 定义为:

Where ClassOrSubclassMatcher is an org.hamcrest.BaseMatcher defined as:

public class ClassOrSubclassMatcher<T> extends BaseMatcher<Class<T>> {

    private final Class<T> targetClass;

    public ClassOrSubclassMatcher(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @SuppressWarnings("unchecked")
    public boolean matches(Object obj) {
        if (obj != null) {
            if (obj instanceof Class) {
                return targetClass.isAssignableFrom((Class<T>) obj);
            }
        }
        return false;
    }

    public void describeTo(Description desc) {
        desc.appendText("Matches a class or subclass");
    }       
}

呸!我会选择第一个选项,直到您真的需要更好地控制 method() 实际返回的内容:-)

Phew! I'd go with the first option until you really need to get finer control over what method() actually returns :-)

这篇关于Mockito 匹配任何类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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