Search code examples
arraysjunitjunit5assertion

Assert List<String[]> with JUnit 5


I have this test with JUnit 4 assertions:

var actual = valueCaptor.getAllValues();
var expected = List.of(new String[] { "1", " A" }, new String[] { "2", " B" }, new String[] { "3", " C" });
for (int i = 0; i < expected.size(); i++) {
    org.junit.Assert.assertArrayEquals(expected.get(i), actual.get(i));
}

I would like to use JUnit 5 assertions, and I have tried:

Assertions.assertIterableEquals(expected, actual);

But it fails, because the actual arrays are different objects than the expected ones. Is there a way to convert my JUnit 4 assertions in a more concise way with JUnit 5?


Solution

  • Using assertAll is arguably a bit more concise. The major benefit in using it, though, is that you can perform all the assertions and only then fail the test with the information from all of them instead of fast-failing on the first violation like the loop in your current code does. This way, if you have multiple bugs in your code you can fix them all at once instead of having to tackle them one at a time:

    Assertions.assertAll(
        IntStream.range(0, actual.size())
                 .mapToObj(i -> () -> Assertions.assertArrayEquals(expected.get(i),
                                                                   actual.get(i)))
    );