Search code examples
javajunitcollectionsassert

How to assert two Class type ArrayList which contains class type elements?


I have two List something like List<A> listExpected and List<A> listActual. I want to compare the elements of these lists but the problem is some elements of these lists are of Class type so my assertion AssertEqual is getting failed. Any idea how can i assert these two lists without manually asserting each elements one by one because there are more than 30 elements.Thanks. Below is the example of the lists element I am getting

Example

List<A> listExpected =[elem1, elem2, Obj@33322, elem3];
List<A> listActual =[elem1, elem2, Obj@346762, elem3];

Dummy Code

Class CashWire {
    String name = "Name";
    String add = "Address";
    String a;
    String b;
    DeliveryInfo diInfo = new DeliveryInfo(name, add);
    public CashWire(String a, String b, diInfo) {
        this.a = a;
        this.b = b;
        this.diInfo = diInfo;
    }
}

class DeliveryInfo {
    String name;
    String add;
    public DeliveryInfo(String name, String add) {
        this.name = name;
        this.add = add;
    }
}

class Main {
    public m1() {
        List <CashWire> list = (List<CashWire>) obj.getData() //will return object type data                                                                
    //    list =<[CashWire[a = "Some String", b = "Some String", 
    //                        diInfo = DeliveryInfo @7872348]]> 
    }
}

Solution

  • Actually I got a solution which works fine for me

    Mockito offers a reflection-matcher:

    For latest version of Mockito use:

    Assert.assertTrue(new ReflectionEquals(expected, excludeFields).matches(actual));
    

    For older versions use:

    Assert.assertThat(actual, new ReflectionEquals(expected, excludeFields));