[英]Forcing failure from SimpleFileVisitor in a JUnit test
I have implemented a class called InspectFiles which extends SimpleFileVisitor, for use with Files.walkFileTree . 我实现了一个名为InspectFiles的类,该类扩展了SimpleFileVisitor,可与Files.walkFileTree一起使用。
I'm using InspectFiles
to inspect the contents of files in a directory and its child directories. 我正在使用InspectFiles
来检查目录及其子目录中文件的内容。 When one of any specific characters is detected can I fail the test from InspectFiles
? 当检测到任何特定字符之一时,我能否通过InspectFiles
进行测试? I am having a great deal of trouble doing so when InspectFiles.visitFile()
is outside of the scope of the test class. 当InspectFiles.visitFile()
不在测试类范围内时,这样做很麻烦。
@Test
public void invalidPunctuationTest() throws IOException {
Path startingDir = dir.toPath();
InspectFiles inspector = new InspectFiles();
Files.walkFileTree(startingDir, inspector);
}
and 和
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;
}
}
You can test whether the error message "This file contains erroneous characters" has been written to System.err by using the library 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"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.