caarlos0
caarlos0

Reputation: 20633

assertThat vs assertEquals for big String comparison

Everyone says that we should use the new assertThat from Junit, but, for big Strings comparison it's seems to be some lack of feature.

Example:

@Test
public void testAssertThat() throws Exception {
    Assert.assertThat("auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei",
            CoreMatchers.equalTo( "auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" ) );
}

@Test
public void testAssertEquals() throws Exception {
    Assert.assertEquals( "auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei",
            "auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" );
}

assertEquals prints an easier to read error message:

org.junit.ComparisonFailure: expected:<...uihaeuieahuiaehuieah[u]aiehiaueheauihaeuiha...> but was:<...uihaeuieahuiaehuieah[e]aiehiaueheauihaeuiha...>

while assertThat prints this:

java.lang.AssertionError: Expected: "auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" but: was "auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei"

Is there a way to get the same behavior with assertThat?

Upvotes: 4

Views: 15724

Answers (1)

davidxxx
davidxxx

Reputation: 131346

The friendly message org.junit.ComparisonFailure: expected... comes from the fact that it is the way that JUnit works with assertEquals and with String as input. In this way, Junit throws org.junit.ComparisonFailure if the String comparison fails.

In your IDE, the comparison is more readable indeed. For example, in Eclipse, you can double- click on the failed Junit test to display a string comparison.

Like this :

enter image description here

AssertThat has a different semantic and the javadoc says it explicitly : Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value. And as the name implies, AssertionError has a semantic wider.

To conclude : if you want keep the friendly message for String, you should go on using AssertEquals for String comparisons.

Upvotes: 4

Related Questions