Is there a way to match any class argument of the below sample routine?
class A {
public B method(Class<? extends A> 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);
EDIT: One solution is
(Class<?>) any(Class.class)
There is another way to do that without cast:
This solution forces the method
any()
to returnClass<A>
type and not its default value (Object
).If you have no idea which Package you need to import:
OR
How about:
or:
the solution from millhouse is not working anymore with recent version of mockito
This solution work with java 8 and mockito 2.2.9
where
ArgumentMatcher
is an instanceoforg.mockito.ArgumentMatcher
And the use
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:
You lose the exact typing (the
Class<? extends A>
) but it probably works as you need it to.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 anA
or a subclass ofA
:Where
ClassOrSubclassMatcher
is anorg.hamcrest.BaseMatcher
defined as:Phew! I'd go with the first option until you really need to get finer control over what
method()
actually returns :-)