Reputation:
I need to pass Class to argument matcher. Here is what I am doing and my match should return object apiResponse which is not null since I am creating it and passing it along. But, it does not seem to be injecting it; I receive it as null.
I have tried it also with ArgumentMatchers.eq(ApiResponse.class),Mockito.eq(ApiResponse.class), ArgumentMatchers.any(ApiResponse.class) and Mockito.any(ApiResponse.class).
With ArgumentMatchers.any(ApiResponse.class) and Mockito.any(ApiResponse.class), the code won't even compile, and with ArgumentMatchers.eq(ApiResponse.class),Mockito.eq(ApiResponse.class), I receive null on the other side. Please suggest!
ApiResponse apiResponse = new ApiResponse();
apiResponse.setErrcode("0");
apiResponse.setNum_fields_changed("1");
Mockito.when(xmlResponseMapper.parseXMLToObject(any(String.class),ArgumentMatchers.eq(ApiResponse.class))).thenReturn((apiResponse));
Here is where I use this matcher in my class
apiResponse = xmlResponseMapper.parseXMLToObject(response.getBody(), ApiResponse.class);
Did I do something wrong? I am using Java 8.
Upvotes: 1
Views: 7577
Reputation:
It is solved. The issue was actually not with ArgumentMatchers.eq(ApiResponse.class) but with the String, the first parameter being passed in the matcher
Mockito.when(xmlResponseMapper.parseXMLToObject(any(String.class),ArgumentMatchers.eq(ApiResponse.class))).thenReturn((apiResponse));
I was passing null as the first parameter. Once I passed a dummy string, it all went fine and I received apiResponse on the other side.
Upvotes: 1
Reputation: 26522
With ArgumentMatchers.any(ApiResponse.class) and Mockito.any(ApiResponse.class), the code won't even compile
As your method expects a class type, those matchers return an object of specified type.
You need to specify the matcher with the exact class that that you intend to pass:
Mockito.when(xmlResponseMapper.parseXMLToObject(any(String.class),
ArgumentMatchers.eq(QuickBaseApiResponse.class))).thenReturn((apiResponse));
If you pass the ApiResponse
to eq()
, then there wont be a match as ApiResponse.class
and QuickBaseApiResponse.class
are different instances and the method will always resolve to false.
Also the apiResponse
needs to be of type QuickBaseApiResponse
.
Upvotes: 0