【问题标题】:checking equality of string containing characters such as "-","+","/" fails检查包含诸如“-”、“+”、“/”等字符的字符串的相等性失败
【发布时间】:2014-02-22 20:59:40
【问题描述】:

我正在尝试通过将标准输出重定向到 ByteArrayOutputStream 对象来检查控制台输出。我发现这个小代码被剪断了,可以让我做到这一点。但是,使用“-”、“+”等字符无法通过测试。我想知道为什么:

这是 jUnit 测试:

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

//This test is try and test output against the console output,
//but the inclusion of characters '-', '*', '+', and '/' makes
//it especially hard to implement correctly. So abandoning
public class ApplicationTest {
    private final ByteArrayOutputStream outContent=new ByteArrayOutputStream();

    @Before
    public void setUpStreams(){
        System.setOut(new PrintStream(outContent));     
    }

    @After
    public void cleanUpStream(){
        System.setOut(null);
    }

    @Test
    public void test_Test1() {
        //Lexer lex=new Lexer("a+b*c");
        //System.out.print("a b c * + ");
        System.out.format("%s ", "a");
        System.out.format("%s ", "- ");
        String str="a - ";      

                //Test Fails.                       
        assertEquals(outContent.toString(),str);
    }

}

【问题讨论】:

  • 如果您需要我们的帮助,请发布 JUnit 给您的非常解释性的错误消息。
  • 请注意:调用 System.setOut(null) 不会将 System.out 重置为其默认值。您应该在更改 is 之前保留对原始 System.out 的引用,并将其设置回此引用。

标签: java junit bytearrayoutputstream


【解决方案1】:

你在输出中有一个额外的空间。

System.out.format("%s ", "a");
System.out.format("%s ", "- ");
//                         ^
String str="a - ";      

【讨论】:

  • 男孩,你必须读几遍,不是吗。格式化时为“a -”。 “-”后面的两个空格——一个来自“%s”格式,一个来自“-”字符串文字。
  • 只需打印两个字符串并(仔细)观察差异,就可以很容易地诊断出问题。
  • @hotlicks 我总是用方括号括起来打印,这样我就可以清楚地看到前导/尾随空格,尤其是尾随换行符。
  • @Bohemian - 总是有些东西 - 我有点喜欢 >>>..方括号!!)
  • 明白了,那是其他东西的残余,过了一段时间我确信这些字符在输出流中以不同的方式编码。
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2019-04-10
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多