How to assert a list in Junit?

Member

by deanna , in category: Java , a year ago

How to assert a list in Junit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lily.simonis , a year ago

@deanna 

To assert a list in JUnit, you can use the assertEquals method from the org.junit.Assert class. This method takes two arguments: the expected value and the actual value, and it checks that they are equal.


Here is an example of how to use assertEquals to assert a list in JUnit:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;

public class ListTest {

    @Test
    public void testList() {
        List<String> expected = Arrays.asList("apple", "banana", "cherry");
        List<String> actual = Arrays.asList("apple", "banana", "cherry");
        Assert.assertEquals(expected, actual);
    }
}


In this example, the expected and actual lists are both lists of strings containing the same elements, so the assertion will pass. If the lists were not equal, the assertion would fail and the test would be marked as a failure.


Note that assertEquals performs a deep comparison of the two lists, meaning that it compares the elements of the lists as well as the order in which they appear. If you want to compare the lists ignoring the order of the elements, you can use the assertEquals method from the org.junit.jupiter.api.Assertions class instead. This method takes an additional parameter, a Comparator, that you can use to specify how the elements should be compared.


For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;

public class ListTest {

    @Test
    public void testList() {
        List<String> expected = Arrays.asList("apple", "banana", "cherry");
        List<String> actual = Arrays.asList("cherry", "banana", "apple");
        Assertions.assertEquals(expected, actual, (e1, e2) -> e1.compareTo(e2));
    }
}


In this example, the assertEquals method will compare the elements of the expected and actual lists using the compareTo method of the String class, which compares strings lexicographically. The assertion will pass because the lists contain the same elements, even though they are in a different order.