Search code examples
javaarraysassertjunit5

Junit5: Why does using assertArrayEquals() trigger an AssertionFailedError?


Doing some JUnit5 tests in Eclipse, I have a routine that returns a byte[]. So I'm using assertArrayEquals to compare the result. However instead of failing the test on mismatch (red status, increasing Errors:), the test fails (blue status, increasing Failures:). The exception trace looks like this then:

org.opentest4j.AssertionFailedError: array contents differ at index [4], expected: <105> but was: <77>
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:48)
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:36)
    at org.junit.jupiter.api.AssertArrayEquals.failArraysNotEqual(AssertArrayEquals.java:434)
    at org.junit.jupiter.api.AssertArrayEquals.assertArrayEquals(AssertArrayEquals.java:214)
    at org.junit.jupiter.api.AssertArrayEquals.assertArrayEquals(AssertArrayEquals.java:72)
    at org.junit.jupiter.api.AssertArrayEquals.assertArrayEquals(AssertArrayEquals.java:64)
    at org.junit.jupiter.api.Assertions.assertArrayEquals(Assertions.java:565)
[...]

In my specific case the expected result was like "Mississippi", when the actual result was "MissMissppi". So how should I formulate the test correctly? I'm running the JRE with -ea as I'm using assertions.

Example (a changed test scenario, but the same problem):enter image description here


Solution

  • The test fails as expected.

    array contents differ at index [4]

    What is at index [4]?

    "Miss[i]ssippi"

    Dec: 105 Hex: 0x69 Char: "i"

    "Miss[M]issppi"

    Dec: 77 Hex: 0x4D Char: "M"

    Why does it fail with an AssertionFailedError?

    [org.junit.jupiter.api.]Assertions is a collection of utility methods that support asserting conditions in tests. [...] Unless otherwise noted, a failed assertion will throw an AssertionFailedError or a subclass thereof.

    https://junit.org/junit5/docs/snapshot/api/org/junit/jupiter/api/Assertions.html