Pavan Kailash
Pavan Kailash

Reputation: 31

How to create test case asserts for objects in a List of objects?

I have 2 JSON files. Both of which have the same structure containing a List of Objects. I have to use Asserts which check if the keys in objects are equal for both JSON files. Each property is mapped to a variable in a Java class.

For other keys, which may be only Objects/variables, check for assertEquals is straightforward, but when it comes to List of Objects, I am unable to find an approach.

First JSON File

    "cars":[
       {
               "name" : Camry,
               "make" : Toyota
       },
       {
               "name" : Maruti 800,
               "make" : Maruti Suzuki
       }
    ]

Second Json File

    "cars":[
       {
               "name" : Mustang,
               "make" : Coupe
       },
       {
               "name" : Maruti 800,
               "make" : Maruti Suzuki
       }
    ]

The properties, name and make are read and stored in a class called CarDetails. The property "cars" is stored in a class MasterCar. I have to compare the list "cars" in the 1st JSON file with the same in the 2nd file. In the above sample code, I need to be able to create asserts for each property in the JSON file. Example, assertEquals(file1.cars[0].name,file2.cars[0].name). I can manually do this, but if the list contains 50 objects, for instance, it would be tedious to manually create asserts for multiple objects for each property. I want to know if I can iterate through the lists and create asserts independently for each object in the list.

Upvotes: 0

Views: 253

Answers (1)

Narrim
Narrim

Reputation: 570

To my eye each json file represents a list of cars....I would just deserialize the file into a list. You refer to "keys" but you dont define what is a key. In java an object can override equals() to define its own equality. It can also define hashcode() ie

    public class Car(){
        private String model;
        private String make;
        public Car(String make; String model) {
          this.model =  model;
          this.make = make;
        }
       @Override
       public boolean equals(Obj obj){

          return obj instance of Car.class && 
                  make.equals(((Car)obj).getMake()) 
                  && model.equals(((Car)obj).getModel())
       }
       //override hashcode as well
        //define getters

    }

Then you can basically iterate over each list and check if each in list 1 is contained in list 2. ie use List.contains(obj)

You can read more on overriding equals and hashcode here. https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

Upvotes: 1

Related Questions