1

I have found a lot of questions and answers about comparing List objects regardless of the order of their elements, but my problem is more complex: I have two beans that contain, among other properties, a List. I want to perform an assertEquals of the two beans regardless of the order of the elements in the inner lists. Is there a simple way to do this?

Pino
  • 7,468
  • 6
  • 50
  • 69

2 Answers2

0

I guess you can find an answer here. The idea is to use hamcrest asserts.

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class CompareListTest {

    @Test
    public void compareList() {
        List<String> expected = Arrays.asList("String A", "String B");
        List<String> actual = Arrays.asList("String B", "String A");

        assertThat("List equality without order", 
            actual, containsInAnyOrder(expected.toArray()));
    }

}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
nikita_pavlenko
  • 658
  • 3
  • 11
  • 1
    No, I don't want to compare two lists: I want to compare two beans that contains both a List and other properties. – Pino Jun 08 '17 at 10:34
  • @Pino sorry for misunderstandings. It would be great if you add some pieces of code to have a better understanding of your situation – nikita_pavlenko Jun 08 '17 at 11:15
0

When you do assertEquals(expectedObject, actualObject) Behind the scene the junit actually call object's equal method.So my suggestion will be if you override your equal method then you can achieve what you are expecting.

Logic behind assertEqual.

String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
 if (expectedString.equals(actualString)) {
            return formatted + "expected: "
                    + formatClassAndValue(expected, expectedString)
                    + " but was: " + formatClassAndValue(actual, actualString);
        } else {
            return formatted + "expected:<" + expectedString + "> but was:<"
                    + actualString + ">";
        }

Or Apache util available to check two object without equal method overiding

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

API

EqualsBuilder.reflectionEquals( obj1, obj2 )
gati sahu
  • 2,576
  • 2
  • 10
  • 16