Mockito匹配任何类参数

Mockito匹配任何类参数

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

问题描述

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

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

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

我怎样才能始终返回新B(),无论哪个类传递到方法?以下尝试仅适用于 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<?extends A> )但它可能会在您需要它时起作用。

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

第二个涉及更多但如果你真的是真的可以说是更好的解决方案希望确保 method()的参数是 A 或<$的子类c $ c> A :

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 定义为:

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");
    }
}

P!我会选择第一个选项,直到你真的需要更好地控制方法()实际返回: - )

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

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

09-02 15:15