Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Ignore the white Spaces while compare two files? [duplicate]

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

This test method doesn't work. The contents of both files are equals, but they have different number of white spaces.

How can I ignore the white spaces?

like image 712
Dan Avatar asked Apr 27 '15 13:04

Dan


3 Answers

If the problem is in leading/trailing white space:

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

If problem is in file contents, only solution I can think of is to remove all white space from both inputs:

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

where removeWhiteSpaces() method looks like this:

String removeWhiteSpaces(String input) {
    return input.replaceAll("\\s+", "");
}
like image 118
ioseb Avatar answered Oct 09 '22 16:10

ioseb


If the problem is only leading/trailing white spaces, you can compare line by line after trimming both. This does not work if there can also be extra newlines in one file compared to the other.

@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());
}
like image 27
Magnar Myrtveit Avatar answered Oct 09 '22 15:10

Magnar Myrtveit


Iterate over list and trim each line

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

Same with other file.

And then compare new lists.

like image 20
talex Avatar answered Oct 09 '22 15:10

talex