我正在尝试通过将标准输出重定向到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);
}
}
答案 0 :(得分:5)
输出中有一个额外的空格。
System.out.format("%s ", "a");
System.out.format("%s ", "- ");
// ^
String str="a - ";