Mockito anyListOf, anyMapOf, anyCollectionOf deprecated replacement - java

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.

Try this:
ArgumentMatchers.<String,Object>anyMap()
or this:
Map<String,Object> mapToGoIntoTheMock = anyMap()

Related

Redefine ConstraintViolation from hibernate validator

We are using the java EE 7 with Wildfly 10.0. In the last few days I am learning a lot of Bean validation feature that is included in Java EE 7 specification. It sounds promising, as I see many advantages in using annotations for validations including reusabilty and cleaner code.
However the javax.validation.Validator returns a Set of ConstraintViolations.
Now, the ConstraintViolation has a message attached to it which you can get from it with getMesssage(). The type of the message is a String.
However, for our error handling we use a custom type that we created called a Pair<int, String>, to return message to the client including error code and a message.
Here is an example of how our pairs look like:
public static final Pair<Integer, String> NAME_VALIDATION_ERROR = new Pair<Integer, String>(
201, "Name must contain only letters");
Now, this is all in a class called ErrorStrings and it's easy to use because that class contains static methods and when you start typing ErrorStrings. the autocomplete gives you the names of the error pairs you can use. For example NAME_VALIDATION_ERROR.
So, what would be the easiest way to add Pair<int, String> to the ConstraintViolation, so that it can be used to return the response to the client without adding complexity to the code.
I thougth of adding a Hashmap<String, Pair<int, String>> to the ErrorStrings class, and using a message defined in ConstraintViolation as a key, but that would add much complexity to that class as you would have to change a pair and a hashmap when you would like to change or add some error.
I am using a hibernate validator, which is a default implementation for Jave EE, but I am willing to use any other implementation. I would like to know the easiest way, to redefine ConstraintViolation so it has Pair<int, String> in it.
The "easiest" way I know is that you should create your own custom contraints, which would throw custom ConstraintViolation implementations, which could also have a public Pair<Integer, String> getMessagePair() method. But this would be even more complex, as it would require you to reimplement every single validation you do.
Personally I would do the translation from String to Pair<Integer, String> in a new ErrorStringTranslator class. This is a bit cleaner solution than the one you mentioned, but doesn't save you from the complexity of the task.

Calling Java method that uses hash map as a parameter

I have a method in an android application:
public void changeImageView (HashMap<String,String> Detail)
I have been trying to call this method in the onCreate method in the same class.
I have tried:
changeImageView();
and
changeImageView(HashMap<String,String> Detail);
Both of which give me errors. The first gives me an error stating that the parameters are missing - understandable. But when I try the second version, I get an error saying "expression expected" with HashMap<String,String>.
I am probably missing something very obvious and have been unable to find anything online that can answer my question.
First, create an instance of HashMap<String, String>.
Map<String, String> map = new HashMap<>();
After its filling or other operations on the map, pass it as a parameter to your method.
changeImageView(map);
I would suggest you reading about methods on Oracle Tutorials.
HashMap is a collection class available in java.util package.
A method changeImageView() here has a definition which takes a HashMap object of type [Generic Type : Google it to know more about it].
You need to create a HashMap object :
Map<String,String> map=new HashMap<String,String>();
You can add values to the above hashmap as given below :
map.add("key1","value1");
map.add("key2","value3");
depending upon your requirements.
Now you can pass this map object to the changeImageView() method as given below:
changeImageView(map)
Seems like you are a newbie to Java and OOP , please refer any Java basic tutorials . This will help you to build up your basic concepts.

Bukkit Config - get Subsections and safe casting

I have the following config file:
arenas
arena1
info: infotest
info2: info2test
arena2
info: infotest
info2: info2test
So. Now i want to get one arena, and convert it to a arena object, i have a constructor there taking a Map. So i do following:
Arena a = new Arena((Map<String, Object>) getConfig().get("arenas.arena1"));
That is working. But: im getting the following warning in eclipse:
Type safety: Unchecked cast from Object to Map<String,Object>
I undestand why this apperas. but how can i change the way getting the informations to avoid this, so to make a "safe" cast?
And my second question: Now i want to get all the sub Map 's from arenas.""
and initialize them when the plugin loads. How can i get all of them? I cannot find something like arenas.getAll() or i dont know.. something like this.. anyone an idea?
Thank you.
For your first question, you can get the configuration section "arena1" and get all of the values as a Map without any warnings. To do this, use:
config.getConfigurationSection("arenas.arena1").getValues(false);
Alternatively, you can just put #SupressWarnings("unchecked") over the method where you're using that code. Since you know the type you're getting will be a Map, the warning doesn't really mean much, though some developers might consider this bad practice.
For your second question, you can use a similar method. getValues() is essentially a getAll() type of method, it gets a map of all of the keys and values in the section. So you could use:
config.getConfigurationSection("arenas").getValues(false);

How can I override a typesafe config list value on the command line?

I have an application.conf file with a structure like the following:
poller {
datacenters = []
}
I would like to override "datacenters" on the command line.
For other configuration keys whose values are simple types (strings, numbers) I can override using -Dpath.to.config.value=<value>, and this works fine.
However, I can't seem to find a way to do this for lists. In the example above, I tried to set "datacenters" to ["SJC", "IAD"] like so: -Dpoller.datacenters="['SJC', 'IAD']", but I get an exception that the key value is a string, not a list.
Is there a way to signal to the typesafe config library that this value is a list?
An alternative syntax is implemented in version 1.0.1 for this:
-Dpoller.datacenters.0=SJC -Dpoller.datacenters.1=IAD
I had the same issue some weeks ago, and finally dived into the source code to understand what's going on:
This feature is not implemented, it's not possible to define a list using command line argument
Fixing it wouldn't be that hard, but someone need to take time to do it.

How to create a variable name at runtime?

I am not able to create the name of the object at runtime. My statement is:
Map<String,String> objectName+""+lineNumber = new HashMap<String,String>();
It's giving me compiletime error. I want to create the HashMap object at runtime depending upon the line number.
Java is not a interpreted but rather a compiled language. So the compiler does not knows how to handle this. Such a thing might make sense in a scripting language.
If you need a custom Name for a "variable" maybe a construct like the following might make sense:
Map<String,Map<String,String>> varMap = new HashMap<String,Map<String,String>>();
varMap.put(objectName+" "+lineNumber, new HashMap<String, String>());
You can't do this directly in Java (without major tricks)
What you can (and probably should) do:
Put your Map in another map which has the 'variable' name as a key.
If you really want to do that you have to do code generation. For this again you have multiple options:
Generate Java Source Code and compile it
Generate Java Byte Code on the fly. You might wanna look at this list: http://java-source.net/open-source/bytecode-libraries for libraries available.
Having a dynamic object name is of No Use.
At first, it's not possible to give reference a dynamic name. The bigger question is Why do you want to do it?
If, just for learning and doing experiments, I'll suggest you should follow proper exercises.
But, if you are trying to achieve some project requirement, Pls. explain the requirement. There will be some other way to achieve that.

Categories

Resources