【问题标题】:How to Ignore the white Spaces while compare two files? [duplicate]比较两个文件时如何忽略空格? [复制]
【发布时间】:2015-04-27 13:12:26
【问题描述】:

我想创建一个单元测试方法。 Java 版本 - 1.6

@Test
public void TestCreateHtml() throws IOException{

    final File output = parser.createHtml();
    final File expected = new File("src/main/resources/head.jsp");

  assertEquals("The files differ!", FileUtils.readLines(expected), FileUtils.readLines(output));
}

此测试方法不起作用。 两个文件内容相同,但空格数不同。

如何忽略空格?

【问题讨论】:

  • 什么样的空白?字符串前面或结尾的那些,或单词之间的空格?
  • 在字符串的前面和结尾
  • 使用字符串的trim 方法。这将删除前导和尾随空格。
  • 什么都没有替换它们怎么样?
  • 为什么不在expected 文件中输入正确的值?

标签: java file unit-testing compare


【解决方案1】:

如果问题在于前导/尾随空格:

assertEquals(actual.trim(), expected.trim());

如果问题出在文件内容中,我能想到的唯一解决方案是从两个输入中删除所有空格:

assertEquals(removeWhiteSpaces(actual), removeWhiteSpaces(expected));

其中 removeWhiteSpaces() 方法如下所示:

String removeWhiteSpaces(String input) {
    return input.replaceAll("\\s+", "");
}

【讨论】:

    【解决方案2】:

    如果问题只是前导/尾随空格,您可以在修剪两者后逐行比较。如果与另一个文件相比,一个文件中还可能有额外的换行符,则此方法不起作用。

    @Test
    public void TestCreateHtml() throws IOException{
        final File output = parser.createHtml();
        final File expected = new File("src/main/resources/head.jsp");
    
        List<String> a = FileUtils.readLines(expected);
        List<String> b = FileUtils.readLines(output);
    
        assertEquals("The files differ!", a.size(), b.size());
        for(int i = 0; i < a.size(); ++i)
            assertEquals("The files differ!", a.get(i).trim(), b.get(i).trim());
    }
    

    【讨论】:

      【解决方案3】:

      遍历列表并修剪每一行

      List<String> result = new ArrayList<String>();
      for(String s: FileUtils.readLines(expected)) {
          result.add(s.trim());
      }
      

      与其他文件相同。

      然后比较新的列表。

      【讨论】:

        【解决方案4】:

        在比较之前删除前导和尾随空格:

        @Test
        public void TestCreateHtml() throws IOException{
        
            final File output = parser.createHtml();
            final File expected = new File("src/main/resources/head.jsp");
        
            assertEquals("The files differ!", FileUtils.readLines(expected).replaceAll("^\\s+|\\s+$", ""), FileUtils.readLines(output).replaceAll("^\\s+|\\s+$", ""));
        }
        

        【讨论】:

          猜你喜欢
          • 2019-05-15
          • 2012-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-25
          • 1970-01-01
          • 2018-10-01
          • 1970-01-01
          相关资源
          最近更新 更多