繁体   English   中英

2 个相同的字符串,在 Junit 测试中进行比较时,它告诉我它们不相等

[英]2 same Strings , when compared in a Junit test it tells me they are not equal

我尝试比较 this.txt

USER bonb Bird
USER colc Colin Cook
EVENT alea Class ULE 11/11/2011 9:00 11/11/2011 13:00
EVENT alea Meeting MIC 11/11/2011 13:00 11/11/2011 14:00
EVENT alea Lunch Cafeteria 11/11/2011 14:00 11/11/2011 15:00
EVENT bonb Class ULE 11/11/2011 15:00 11/11/2011 19:00
EVENT bonb Meeting Library 11/11/2011 13:00 11/11/2011 14:00

在我的 class File.java 中,我使用此方法将 txt 的内容转换为字符串。

public String readElements() throws FileException {
        FileReader fr = null;
        BufferedReader br = null;
        StringBuilder line = new StringBuilder();
        String lineAux = "";

        logger.info("Reads an element of the file: " + this.fileName);

        try {
            fr = new FileReader(this.fileName);
            br = new BufferedReader(fr);

            lineAux = br.readLine();
            while (lineAux != null) {
                line.append(lineAux + System.getProperty("line.separator"));
                lineAux = br.readLine();
            }
        } catch (IOException e) {
            logger.warn("File Error: Can´t open the file: " + this.fileName);
            throw new FileException("File Error: Can´t open the file " + this.fileName);
        } finally {
            try {
                if (null != fr) {
                    fr.close();
                }
            } catch (IOException e) {
                logger.warn("File error: Can´t open the file: " + this.fileName);
                throw new FileException("File error: Can´t open the file: " + this.fileName);
            }
        }
        return line.toString();
    }

我使用这个测试来尝试 File.Java TestReadElements 将该字符串与文件的内容进行比较。 而当我在 eclipse 或 build.xml 中使用 Junit 时,终端测试失败了。

@Before
    public void setUp() throws Exception {
        this.fileName = "./etc/test/rightCalendar.txt";
        this.file = new File(this.fileName);
    }

@Test
    public void testReadElements() throws FileException {
        assertEquals("USER alea Alex Archer\n" + "USER bonb Bonnie Bird\n" + "USER colc Colin Cook\n"
                + "EVENT alea Class ULE 11/11/2011 9:00 13:00\n" + "EVENT alea Meeting MIC 11/11/2011 13:00 14:00\n"
                + "EVENT alea Lunch Cafeteria 11/11/2011 14:00 15:00\n"
                + "EVENT bonb Class ULE 11/11/2011 15:00 19:00\n"
                + "EVENT bonb Meeting Library 11/11/2011 13:00 14:00\n", this.file.readElements());
    }

我不知道问题出在哪里(如果问题在 build.xml 或其他文件中)我已经改变了几个小时的小东西,我很累......这些是路径文件和比较告诉我不正确

您正在使用System.getProperty("line.separator")显式连接从阅读器读取的行; 您的屏幕截图表明您在 Windows 上运行它(路径以C:\Users开头),它使用\r\n作为行分隔符。

您预期的字符串行使用\n作为行分隔符。

因此,字符串不相等,因为它们使用不同的行分隔符。

最好将事物保留为字符串列表,然后只比较列表( List.equals对元素进行成对比较,因此它实际上是相同的——只是对行分隔符没有任何混淆)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM