Mockito matches a specific class argument
I am trying to mock some resources that are dynamically generated. To generate these resources, we must pass a class argument. For example:
FirstResourceClass firstResource = ResourceFactory.create(FirstResourceClass.class);
SecondResourceClass secondResource = ResourceFactory.create(SecondResource.class);
This is good and good until I try to scoff. I am doing something like this:
PowerMockito.mockStatic(ResourceFactory.class);
FirstResourceClass mockFirstResource = Mockito.mock(FirstResourceClass.class);
SecondResourceClass mockSecondResource = Mockito.mock(SecondResourceClass.class);
PowerMockito.when(ResourceFactory.create(Matchers.<Class<FirstResourceClass>>any()).thenReturn(mockFirstResource);
PowerMockito.when(ResourceFactory.create(Matchers.<Class<SecondResourceClass>>any()).thenReturn(mockSecondResource);
The layout seems to be injected into the calling class, but FirstResourceClass
dispatched mockSecondResource
, which causes a compilation error.
The problem is (I think) using any () (which I got from this question ). I believe I need to use isA()
, but I'm not sure how to do it as it requires an argument Class
. I tried FirstResourceClass.class
and it gives a compilation error.
source to share
You want eq
like in:
PowerMockito.when(ResourceFactory.create(Matchers.eq(FirstResourceClass.class)))
.thenReturn(mockFirstResource);
any()
ignores the argument, but isA
checks that your argument is of a specific class, but does not mean that it is equal to the class, namely instanceof
for a specific class. ( any(Class)
has semantics any()
in Mockito semantics 1.x and isA
2.x.)
isA(Class.class)
is less specific than you need to differentiate your calls, so eq
this is. Class objects have well-defined equality anyway, so this is easy and natural for your use case.
Since this eq
is the default if you are not using sockets this also works:
PowerMockito.when(ResourceFactory.create(FirstResourceClass.class))
.thenReturn(mockFirstResource);
Note that newer versions of Mockito do not favor the name Matchers in favor of ArgumentMatchers, and it Mockito.eq
also works (albeit clumsily because they "inherit" static methods).
source to share