I have seen in many Rest Assured frameworks that we create POJO classes for Serialization & deserialization but let's say we have to automate more than 50-70 APIs thus, creating POJO classes for all seems tedious work so can we deal with JSON objects and data directly? We can get rid of getters and setters by using Lombok annotations but still, we will have to set variables. just curious about what should be the best practice we can follow?
CodePudding user response:
Not sure if I understood correctly. So maybe this answer goes in the totally wrong direction.
If you have lots of Classes and member variables, to streamline handling, you could introduce a level of abstraction. As an example:
- instead of a class and its member variables, you could have a HashMap that stores [variable name] as key, and [variable value] as value.
- for multiple object of the same class, instantiate multiple HashMaps
- maybe hold all those produced HashMaps in a Collection like a List
- maybe even have an 'outer' HashMap, that maps [class name] to [collection]
- in the end it might look like this: HashMap[class name -> Collection], Collection contains multiple 'object' HashMaps. Object HashMaps map their [member variable name] to the [meber variable value]
Now, to the JSON part: Google's GSON already has classes in place that do exactly that (object abstraction), so you now have an easy bridge between JSON and Java.
And then you bring it all together and only write ONE serializer and ONE deserializer for ALL classes you wanna handle.
CodePudding user response:
In the end, you still have to put value to POJO or any kinds of object (Map, List, JSON objects...) to create a json payload. I don't like the idea manipulating data directly, it's so rigid. To make your work less tedious, some techniques can be applied:
- Create inner classes if you don't want to create too many POJO classes separatly.
- Use Builder pattern (Intellij suggestion or @Builder annotation in lombok) to create POJO instance more straightforward (comparing to basic Setter).
- Create POJO instance with default value for each property, then only the property that matters.
- Separate the creation of POJO object in other packages, like
PersonFactoryto buildPersoninstance. It will help make test cleaner.
