assertThat vs assertEquals用于大字符串比较

时间:2015-01-30 13:07:23

标签: junit4

每个人都说我们应该使用来自Junit的新assertThat,但是,对于大字符串比较,它似乎缺乏某些功能。

示例:

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

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

assertEquals打印出更易于阅读的错误消息:

  

org.junit.ComparisonFailure:   预期:其中... uihaeuieahuiaehuieah [U] aiehiaueheauihaeuiha ...>但   是:其中... uihaeuieahuiaehuieah并[e] aiehiaueheauihaeuiha ...>

assertThat打印出来:

  

java.lang.AssertionError:预期:   " auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei"        但是:" auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaehaeiaehuiaehuiaehuiaehaeehaei"

有没有办法让assertThat获得相同的行为?

1 个答案:

答案 0 :(得分:3)

友好消息org.junit.ComparisonFailure: expected...来自这样一个事实:它是JUnit与assertEquals一起使用并使用String作为输入的方式。 这样,如果String比较失败,Junit将抛出org.junit.ComparisonFailure。

在IDE中,比较更具可读性。例如,在Eclipse中,您可以双击失败的Junit测试以显示字符串比较。

像这样:

enter image description here

AssertThat有不同的语义,javadoc明确地说: Asserts that actual satisfies the condition specified by matcher. If not, an AssertionError is thrown with information about the matcher and failing value. 顾名思义,AssertionError的语义更广泛。

总结:如果你想保留String的友好消息,你应该继续使用AssertEquals进行字符串比较。