Eclipse junit视图中的不可打印字符

时间:2014-01-28 22:28:05

标签: 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

3 个答案:

答案 0 :(得分:2)

对于断言必须对“不可打印字符”敏感的情况,您可以使用自定义断言方法,在比较之前将非可打印字符转换为其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;
}
}

答案 1 :(得分:1)

您可以编写自己的断言方法(不使用Assert类中的任何一个)抛出junit.framework.ComparisonFailure.ComparisonFailure,其中包含以显示不可打印字符的方式转换的预期值和实际值(如@GuyBouallet回答中的replaceNonPrintable(String)方法)。该自定义断言不能使用Assert.assertEquals(),因为它会抛出原始对象(在您的情况下为字符串)作为参数的异常;你需要使用修改版本的输入抛出异常。

答案 2 :(得分:0)

首先检查其他测试框架,如assertj和hamcrest matchers。他们有更好的报告部分 - 他们可能有开箱即用的功能。

如果没有,那么: 如果你期望在这个唯一的测试中遇到这个问题那么就像@Guy Bouallet所说的那样 - 编写你自己的断言。但是如果你的应用程序做了很多这种字符串比较,而不是编写许多不同的asertions(equals / substring / matches等),那么只需使用字符串规范化。在将字符串传递给assert方法之前,将所有白色字符替换为其他字符

相关问题