2014-04-02 142 views
0

我實現了一個名爲InspectFiles的類,該類擴展了SimpleFileVisitor,與Files.walkFileTree一起使用。在JUnit測試中強制SimpleFileVisitor失敗

我使用InspectFiles來檢查目錄及其子目錄中的文件內容。當檢測到某個特定字符時,我可以通過InspectFiles的測試失敗嗎?當InspectFiles.visitFile()超出測試類的範圍時,我遇到了很大的麻煩。

@Test 
public void invalidPunctuationTest() throws IOException { 
    Path startingDir = dir.toPath(); 
    InspectFiles inspector = new InspectFiles(); 

    Files.walkFileTree(startingDir, inspector); 
} 

public class InspectFiles extends SimpleFileVisitor<Path> { 
    @Override 
    public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { 

     try { 
      File currentFile = new File(file.toString()); 
      InputStreamReader stream = new InputStreamReader(new FileInputStream(currentFile)); 
      for (int i = stream.read(); i != -1; i = stream.read()) { 
       char c = (char) i; 

       if (c == '’' || c == '–') { 
        throw new AssertionError(); 
       } 
      } 
     } 
     catch (final IOException e) { 
      e.printStackTrace(); 
     } 
     catch (final AssertionError e) { 
      System.err.println(e + " This file contains erroneous characters: " + file.toString()); 
      e.printStackTrace(); 
     } 
     return FileVisitResult.CONTINUE; 
    } 
} 

回答

1

您可以通過使用圖書館System Rules

@Rule 
public final StandardErrorStreamLog log = new StandardErrorStreamLog(); 

@Test 
public void invalidPunctuationTest() throws IOException { 
    Path startingDir = dir.toPath(); 
    InspectFiles inspector = new InspectFiles(); 
    Files.walkFileTree(startingDir, inspector); 
    assertFalse(log.getLog().contains("This file contains erroneous characters")); 
} 
測試錯誤消息是否「此文件包含錯誤的字符」已被寫入System.err的