Search code examples
javajuniterror-handlingassertions

JUnit AssertionFailedError: Text in the file differs in java


I am using JUnit Test for testing purposes, but I am facing a problem of AssertionFailedError. I am using command line arguments to pass Test cases to the main class.

Below is my Main.java code

public class Main {

public static void main(String[] args) throws IOException {


    //Storing all the commands, words, files
    ArrayList<String> commands = new ArrayList<>();
    ArrayList<String> words = new ArrayList<>();
    ArrayList<String> files = new ArrayList<>();

    for(String arg: args){
        if(arg.contains("."))
            files.add(arg);
        else if(arg.contains("-") && !arg.contains("--"))
            commands.add(arg);
        else{
            if(!arg.contains("--"))
            words.add(arg);
        }
    }

    for(String file : files ){

        File originalFile = new File(file);

        //CHECK IF textFile exists
        if(originalFile.exists()){
            if(words.size() == 2){
                String from = words.get(0), to=words.get(1);
                BufferedWriter bw;
                //If file exists then check command
                for(String command : commands){
                  if(command.trim().contains("-f")){
                        File temp = new File("Temp.txt");
                        temp.createNewFile();
                        //If Temp.exists
                        if(temp.exists()){
                            bw = new BufferedWriter(new FileWriter(temp));

                            //Fetch all the lines from Orginal File
                            List<String> lines = Files.readAllLines(Paths.get(originalFile.getName())); 

                            //Add to treemap
                            TreeMap<Integer,String> tm = new TreeMap<>(); 
                            for(int i=0;i<lines.size();i++){
                                tm.put(i,lines.get(i));
                            }

                            //To check first occurence of word in hashmap
                            for(int i=0;i<tm.size();i++){
                                String lastLine = tm.get(i);
                                tm.remove(i);
                                tm.put(i,lastLine.replaceFirst(from,to));
                                if(!lastLine.equals(tm.get(i)))
                                    break;
                            }

                            //Write treemap to the text file
                            for(String line: tm.values())
                                bw.write(line.trim() + "\n");
                            System.out.println("First Occurence " + originalFile.getName()+ " changed");
                            bw.close();
                            originalFile.delete();
                            temp.renameTo(originalFile);
                        }else
                            System.out.println("Error in creating Temp.txt file");
                    }
                 }
              }

Everything is working fine, the file is created. I dont think there is error in the code. Below is the MainTest.java

public class MainTest {

// Some utilities

private File createInputFile1() throws Exception {
    File file1 =  new File("Test.txt");
    try (FileWriter fileWriter = new FileWriter(file1)) {
        fileWriter.write("Dog is an animal");
    }
    return file1;
}

private String getFileContent(String filename) {
    String content = null;
    try {
        content = new String(Files.readAllBytes(Paths.get(filename)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

// Actual test cases
@Test
public void mainTest2() throws Exception {
    File inputFile1 = createInputFile1();

    String args[] = {"-f", "Dog", "Cat", "--", "Test.txt"};
    Main.main(args);

    String expected1 = "Cat is an animal".trim();

    String actual1 = getFileContent("Test.txt");

    assertEquals("The files differ!", expected1, actual1);
    assertTrue(Files.exists(Paths.get(inputFile1.getPath() + ".bck")));
}

}

Everything works fine, file Test.txt is created and it has the text in it. But I am facing this error of AssertionFailedError: The files differ! expected: Cat is an animal[] but was: Cat is an animal[ ]

Why does it differ [] and [ ] ?


Solution

  • Try this, shall help :

    String expected1 = "Cat is an animal".trim();
    
    String actual1 = getFileContent("Test.txt").trim();
    
    assertEquals("The files differ!", expected1, actual1);
    

    Since what trim does is

     * @return  A string whose value is this string, with any leading and trailing white
     *          space removed, or this string if it has no leading or
     *          trailing white space.
    

    hence you see a diff of space [ ] and [] with your solution and its resolved using trim in both.