Search code examples
javaunit-testingtestingjunithamcrest

Unit test failing with Junit and Hamcrest - Not able to compare data with two List objects


I have the following test that is actually asserting the data within two Lists. But even though the data is same, the test does not pass. I googled and found SO links which pointed to using assertThat(actual, containsInAnyOrder(expected.toArray())); but no luck.

@Test
public void testGetOrderLines() {
    List<OrderLine> expResult = new ArrayList<>();
    OrderLine orderLine = new OrderLine(100, 5, "http://image-url.com", "Baby Gym",
            1, "physical", "http://product-url.com", 100, "pcs", "100-123");
    expResult.add(orderLine);
    List<OrderLine> result = instance.getOrderLines();
    assertThat(expResult, containsInAnyOrder(result.toArray()));
}

Error:

Failed tests: AuthorizationRequestTest.testGetOrderLines:92 Expected: iterable over [http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>] in any order but: Not matched: http://image-url.com,name=Baby Gym,quantity=1,type=physical,productUrl=http://product-url.com,unitPrice=100,quantityUnit=pcs,reference=100-123]>


Solution

  • If you have no chance to implement an equals() method you may use a reflection based equality-assertion. e.g. unitils. It also works on objects contained in lists or arrays. Be aware that if the order may differ, you must use the lenient order comparator mode. Here is an example:

    import static org.junit.Assert.*;
    import org.junit.Test;
    import org.unitils.reflectionassert.ReflectionComparatorMode;
    import static org.unitils.reflectionassert.ReflectionAssert.*;
    import java.util.Arrays;
    import java.util.List;
    
    public class ReflectionEqualsTest {
    
        public static class A {
            private String x;
    
            public A(String text) {
                this.x = text;
            }
        }
    
        @Test
        public void testCompareListsOfObjectsWithoutEqualsImplementation() throws Exception {
            List<A> list = Arrays.asList(new A("1"), new A("2"));
            List<A> equalList = Arrays.asList(new A("1"), new A("2"));
            List<A> listInDifferentOrder = Arrays.asList(new A("2"), new A("1"));
    
            assertNotEquals(list, equalList);
            assertNotEquals(list, listInDifferentOrder);
    
            assertReflectionEquals(list, equalList);
            assertReflectionEquals(list, listInDifferentOrder, 
                            ReflectionComparatorMode.LENIENT_ORDER);
        }
    }