Search code examples
javamockitodeprecated

Mockito anyListOf, anyMapOf, anyCollectionOf deprecated replacement


I am working on a Java 8 to Java 17 update and the project includes a very old version of Mockito. When I update the library to Mockito 4.4.0 I found out that there many libraries which has been completely removed, most of them are related with validation of objects that you can set the variable type at compilation time, for instance: If you have the following object:

Map<String,Object> map

Then you can validate with Mokito if the map is of type String, Object by using:

anyMapOf(String.class,Object.class)

The thing in here is that I thought that one of this both could be a good approach:

//Create the map first 
Map<String,Object> map = new HashMap<>();
//Then use the method "any" calling the getClass method 
any(map.getClass())

But now I'm pretty sure that it is not the same. On the other hand, I found the following forum: java generics: getting class of a class with generic parameters

From which I get this code:

(Class<Map<String,Object>>)(Class)Map.class

This also seems to work if you use it with any, like so:

any((Class<Map<String,Object>>)(Class)Map.class)

But obviously, it triggers a warning message and it doesn't seem to be the best solution.

Finally, I read in the Mockito documentation that this clases were only used for generic friendliness to avoid casting before Java 8, so that means that if I use anyMap in Java 8 and upwards it will work the same as anyMapOf?

I have been searching for hours for which could be the best replacement for this deprecated method but I just can't find the right answer.


Solution

  • Try this:

    ArgumentMatchers.<String,Object>anyMap()
    

    or this:

    Map<String,Object> mapToGoIntoTheMock = anyMap()