alexdis
alexdis

Reputation: 19

Can you use JUnit to compare two String ArrayLists?

For example, if you have the following two ArrayLists:

ArrayList<String> arrLst1 = new ArrayList<String>();
arrLst1.add("Hello");
arrLst1.add("Goodbye");

ArrayList<String> arrLst2 = new ArrayList<String>();
arrLst2.add("Greetings");
arrLst2.add("See you soon");

If I wanted to use JUnit, my guess would be to use something like this:

import static org.junit.Assert.*;
import org.junit.Test;
import java.util.*;

public class myTest {
  @Test
  public void firstTest() {
    assertArrayEquals("Error Message", arrLst1, arrLst2);
  }
}

However, I'm having an issue where once I run the code, it states that the two values are equal. Looking at the documentation, I don't see anything for assertArrayEquals() for two String ArrayLists. Is this even something that is possible?

Upvotes: 0

Views: 1531

Answers (2)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11136

assertArrayEquals is for arrays, and ArrayList<T> is not an array.

JUnit5

Use JUnit5 and:

assertIterableEquals(expected, actual); //from org.junit.jupiter.api.Assertions

will assert that expected and actual iterables are deeply equal.


JUnit4

If you use JUnit4, upgrade to JUnit5; however, if still with 4, then, generally, you will need to override .equals() method in your Generic Type Argument class (T in List<T>), after which, you can use:

assertEquals(expected, actual);

Note, that if your generic argument (typed contained in your list) is String, you do not need (you cannot, actually) override .equals(), since String already overrides it perfectly fine.

Upvotes: 4

Richard Robinson
Richard Robinson

Reputation: 997

You can use assertEquals, which has an overload taking two Object arguments, like so:

import static org.junit.Assert.*;


var a = List.of("hello");
var b = List.of("hello");

assertEquals(a, b); // passes

var c = List.of("hello");
var d = List.of("world");

assertEquals(c, d); // fails

In this case, assertEquals method uses the .equals() overridden method of List to determine if both lists contain the same contents.

Upvotes: 2

Related Questions