junit4 icon indicating copy to clipboard operation
junit4 copied to clipboard

Throw ComparisonFailure rather than AssertionError for all equals methods

Open liamsharp opened this issue 8 years ago • 6 comments

I'd like to propose a change that I think would make the assertEquals methods easier to work with - apologies if I've missed something.

When a test fails in Eclipse with assertEquals() and the parameters are not strings, an AssertionError is thrown. This gives a backtrace, but to see what was not equal, I have to copy and paste out the error into another editor to read the top line. Here's a screen shot:

screen shot 2017-02-03 at 18 49 26

It would be great if could throw a ComparisonFailure. I'd still see pretty much the same failure trace:

screen shot 2017-02-03 at 18 52 05

but I'd be about to double click it/click the "Compare with Expected Results" button and get this:

screen shot 2017-02-03 at 18 52 20

which would be a tremendous help to my work flow.

When looking into this I did think surely Eclipse could do something better, but I don't think it can. An AssertionError doesn't have the expected and actual results. They are thrown away by the call to failNotEquals which calls 'format' that then concatenates a single string to pass to AssertionError

So looking at assertEquals for Object's could we just do away with the instanceof checks?

public static void assertEquals(String message, Object expected,
            Object actual) {
        if (equalsRegardingNull(expected, actual)) {
            return;
        }
        if (expected instanceof String && actual instanceof String) {
            String cleanMessage = message == null ? "" : message;
            throw new ComparisonFailure(cleanMessage, (String) expected,
                    (String) actual);
        } else {
            failNotEquals(message, expected, actual);
        }
    }

liamsharp avatar Feb 03 '17 19:02 liamsharp

We would most likely do this by integrating with https://github.com/ota4j-team/opentest4j but we need some changes there so JUnit4 can use those APIs. See https://github.com/ota4j-team/opentest4j/issues/27

kcooney avatar Feb 03 '17 19:02 kcooney

Incidentally, the reason why this isn't so simple is you might get an exception when calling toString() on the expected and/or actual values.

kcooney avatar Feb 04 '17 02:02 kcooney

wow ,I want to learn,but it can't load .can you send me resoure to load the Junit4.Thanks

xcjm avatar Feb 22 '17 02:02 xcjm

my email [email protected].

xcjm avatar Feb 22 '17 02:02 xcjm

@xcjm http://javarevisited.blogspot.com/2014/08/top-5-books-to-learn-unit-testing-junit-tdd-Java-programmers.html?m=1

kcooney avatar Feb 22 '17 04:02 kcooney

Incidentally, the reason why this isn't so simple is you might get an exception when calling toString() on the expected and/or actual values.

We could put catches around the toString() calls and fallback to Object.toString() if they throw.

j256 avatar Jan 04 '21 16:01 j256