java - Eclipse junit View 中的不可打印字符

标签 java eclipse unit-testing testing junit

考虑以下示例:

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”(或其他不可打印的字符)?

目前的结果比较并不能真正帮助我识别问题: extra carriage return result comparison

最佳答案

对于断言必须对“不可打印字符”敏感的情况,您可以使用自定义断言方法,该方法在比较之前将不可打印字符转换为其 unicode 表示形式。这是一些快速编写的代码用于说明(受到 thisthis 的启发):

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;
}
}

关于java - Eclipse junit View 中的不可打印字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418265/

相关文章:

java - 如何为嵌入式mongo(flapdoodle)全局设置WriteConcern以修复间歇性测试失败

java - Android:加载、操作和使用图像

java - 将带有周和年的字符串解析为 LocalDate

java - 在 JavaFx 中重新启动应用程序

java - 如何将对象转换为 List<Object[]> 类型?

eclipse - Maven-Dependency-Plugin:Aether RepositorySystem 的 NoSuchElementException

python - 为什么所有模块一起运行?

java - 我可以使用 Android 的测试框架测试状态栏通知吗?

ruby-on-rails - Rails测试默认请求主机

java - 使用@RunWith(SpringJUnit4ClassRunner.class),可以访问ApplicationContext对象吗?