How to ignore white spaces when comparing two files?

I want to create a Unit test method. Java Version 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));
}

This testing method does not work. The contents of both files are equal, but they have a different number of spaces.

How to ignore spaces?

+4
source share
4 answers

If the problem is spaces at the beginning / end:

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

If the problem is with the contents of the file, the only solution I can come up with is to remove all spaces from both inputs:

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

where the removeWhiteSpaces () method looks like this:

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

/ , . , .

@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());
}
+1

Scroll through the list and crop each line

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

Same thing with another file.

And then compare the new listings.

+1
source

Just remove the leading and trailing spaces before comparing:

@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+$", ""));
}
0
source

Source: https://habr.com/ru/post/1584903/


All Articles