【发布时间】: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