有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查包含诸如“”、“+”、“/”等字符的字符串的相等性失败

我试图通过将标准输出重定向到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);
    }

}

共 (1) 个答案

  1. # 1 楼答案

    输出中有一个额外的空间

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