我实现了一个名为InspectFiles的类,该类扩展了SimpleFileVisitor,供Files.walkFileTree使用。

我正在使用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;
    }
}

最佳答案

您可以使用库System Rules来测试是否将错误消息“此文件包含错误字符”写入System.err。

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

10-07 20:44