對於情況下,斷言必須是「非打印字符」敏感,你可以使用它轉換非打印自定義斷言方法字符與比較之前的Unicode字符表示。這裏是一個用於說明一些快速編寫的代碼(由this和this啓發):拋出與預期和junit.framework.ComparisonFailure.ComparisonFailure
package org.gbouallet;
import java.awt.event.KeyEvent;
import org.junit.Assert;
import org.junit.Test;
public class NonPrintableEqualsTest {
@Test
public void test() {
assertNonPrintableEquals(
"I am expecting this value on one line.\r\nAnd this value on this line",
"I am expecting this value on one line.\nAnd this value on this line");
}
private void assertNonPrintableEquals(String string1,
String string2) {
Assert.assertEquals(replaceNonPrintable(string1),
replaceNonPrintable(string2));
}
public String replaceNonPrintable(String text) {
StringBuffer buffer = new StringBuffer(text.length());
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (isPrintableChar(c)) {
buffer.append(c);
} else {
buffer.append(String.format("\\u%04x", (int) c));
}
}
return buffer.toString();
}
public boolean isPrintableChar(char c) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return (!Character.isISOControl(c)) && c != KeyEvent.CHAR_UNDEFINED
&& block != null && block != Character.UnicodeBlock.SPECIALS;
}
}
這是一個小故障,但仍然不是一個壞主意。然而,改變單元測試數據本身似乎有點有趣,但我明白爲什麼。理想情況下,這樣的東西將被整合到junit插件中。 +1 – javamonkey79