[英]non printable characters in Eclipse junit view
考虑以下示例:
assertEquals( "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" );
\\ Eclipse中是否有任何调整或插件可以帮助在字符串比较中识别额外的'r'(或其他不可打印的字符)?
当前的结果比较并不能真正帮助我确定问题所在:
对于断言必须对“不可打印字符”敏感的情况,您可以使用自定义断言方法,该方法将不可打印字符转换为它们的unicode表示形式,然后进行比较。 这是一些快速编写的示例代码(受this和this启发):
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;
}
}
您可以编写自己的断言方法(不使用Assert
类中的任何方法),该方法将抛出junit.framework.ComparisonFailure.ComparisonFailure
,并以显示不可打印字符(例如replaceNonPrintable(String)
由@GuyBouallet答案的方法)。 该自定义断言不能使用Assert.assertEquals()
因为它会将原始对象(在您的情况下为Strings)作为参数抛出异常。 您需要使用输入的修改版本引发异常。
首先检查其他测试框架,例如assertj和hamcrest匹配器。 他们具有更好的报告功能-他们可能具有此功能。
如果不是,则:如果您希望在唯一的一次测试中出现此问题,请按照@Guy Bouallet所说的-编写您自己的断言。 但是,如果您的应用程序进行了大量此类字符串比较,而不是编写许多不同的断言(等于/子字符串/匹配项等),则只需使用字符串规范化即可。 在将字符串传递给assert方法之前,将所有白色字符替换为其他字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.