Home > Back-end >  Eclipse JUnit assertEquals(String, String) - disable square bracket diff in Failure Trace
Eclipse JUnit assertEquals(String, String) - disable square bracket diff in Failure Trace

Time:09-17

JUnit assertEquals Changes String
In short: assertEquals("Hello World", "HelloWorld"); appears in the Failure Trace as expected:<Hello[ ]World> but was:<Hello[]World>
Great. Definitely didn't waste my time trying to figure out why the heck my parser was randomly throwing square brackets around.

How do I disable this?

I am using Eclipse 4.19.0 for Java, JUnit 4.10.

CodePudding user response:

You cannot.

These brackets are added by junit.framework.ComparisonCompactor that is being used in org.junit.ComparisonFailure assertion error's getMessage method (this error is being thrown by assertEquals btw)

// ComparisonFailure class
public String getMessage() {
    return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage());
}

in ComparisonCompactor these brackets are hardcoded and it seems that there is no configuration that can be provided, also ComparisonCompactor cannot be injected (the same for ComparisonFailure - you are not able to provide custom implementation for them)

public class ComparisonCompactor {

    private static final String ELLIPSIS= "...";
    private static final String DELTA_END= "]";
    private static final String DELTA_START= "[";

    // ...

    private String compactString(String source) {
        String result= DELTA_START   source.substring(fPrefix, source.length() - fSuffix   1)   DELTA_END;

As far as I see even in Junit 4.13 it looks exactly the same so even bumping up dependency will not help here (however you could give a try to Junit5 that with usage of Assertions.assertEquals will produce expected: <Hello world> but was: <Helloworld> output - but obviously it won't be just bumping up dependency version)

By the way Eclipse has nothing to do with it, the same output you will get in other IDEs (or in console)


What I would suggest (however it's not an answer for your question) is to use assertion library like AssertJ that can give you more control but also make you assertions more fluent.

An example in AssertJ would look like

assertThat("Hello World").isEqualTo("HelloWorld");

and is producing

Expecting:
 <"Hello World">
to be equal to:
 <"HelloWorld">
but was not.
  • Related