2016-11-17 4 views
0

Я использую JUnit Test для тестирования, но перед проблемой AssertionFailedError возникает проблема. Я использую аргументы командной строки для передачи тестовых примеров в основной класс.JUnit AssertionFailedError: текст в файле отличается в java

Ниже мой Main.java код

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"); 
        } 
       } 
       } 

Все работает отлично, файл создается. Я не думаю, что в коде есть ошибка. Ниже 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"))); 
} 

} 

Все работает отлично, файл Test.txt создается и имеет текст в нем. Но я столкнулся с этой ошибкой AssertionFailedError: Файлы отличаются! ожидаемый: Cat является животным [], но был: Cat является животным []

Почему он отличается [] и []?

+0

Почему вы обрезаете литерал 'String'' String expected1 = «Cat - это животное» .trim(); 'который не нуждается в обрезке. Вы хотите обрезать содержимое файла? – bradimus

+0

Что такое кодировка файла? Он может иметь байтовую кодировку и ваше утверждение будет ... – Palcente

ответ

0

Попробуйте это, должно помочь:

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

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

assertEquals("The files differ!", expected1, actual1); 

С чего trim делает

* @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. 

поэтому вы видите диф пространства [ ] и [] с раствором и его решена с помощью отделки в обоих.

+1

Это работает !! Можешь мне сказать почему ? – topper1309

+0

@ topper1309 отредактировал ответ – nullpointer