使用 JUnit assertEquals()
,我正在比较空白/控制字符可能不同的字符串。
特别是“\r\n”与“\n”。
当字符串以这种方式不同时,由于某些原因,assertEquals()
的错误输出很难解释。
- 它们是空白字符,不适合目视检查
- \r 字符会导致输出被覆盖。
此示例显示了如果字符串中没有任何特殊字符,通常如何测试字符串 */
@Test
public void testIfTheCarriageReturned()
{
final String expected = "we're taking\r\n the hobbits\r\n to Isengard!";
final String actual = "we're taking\n the hobbits\n to Isengard!";
assertEquals(expected, actual);
}
此示例正确确定字符串不同,但 JUnit 的输出并没有清楚地表明它们有何不同(空白不以任何特殊方式处理)。
有没有办法让 JUnit 产生更合适的输出?
最佳答案
说实话,我想这不是关于格式化,而是关于正确编写测试。我从来不关心 Junit5 的新功能,因此可能有一种新的 super 智能方法来实现这一点,但是是的:
@Test
public void testIfTheCarriageReturned()
{
/**
* This is how you'd normally test string if you wouldn't have any special chars within
*/
final String expected = "we're taking\r\n the hobbits\r\n to Isengard!";
final String linuxGuy = "we're taking\n the hobbits\n to Isengard!";
//assertEquals(expected, linuxGuy);
/**
* Just do it charwise...
*/
for(int i = 0; i<expected.length(); i++)
{
assertEquals("Character differed at index "+i,Character.getName(expected.charAt(i)), Character.getName(linuxGuy.charAt(i)));
}
}
这基本上只是获取角色的名称并比较它们在同一索引处是否相等。
这将导致以下输出:
org.junit.ComparisonFailure: Character differed at index 12 expected:<[CARRIAGE RETURN (CR])> but was:<[LINE FEED (LF])>
at org.junit.Assert.assertEquals(Assert.java:117)
补充一下: 当实际字符串比预期字符串长时,这将导致测试通过。您可以随后检查长度,也可以在循环后对两个字符串使用assertEquals 方法。出于品味问题,我可能更喜欢后者。
关于junit - JUnit 消息的格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70687980/