我实现了一个名为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;
}
}
答案 0 :(得分:1)
您可以使用库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"));
}