I have implemented a class called InspectFiles which extends SimpleFileVisitor, for use with Files.walkFileTree .
I'm using InspectFiles
to inspect the contents of files in a directory and its child directories. When one of any specific characters is detected can I fail the test from InspectFiles
? I am having a great deal of trouble doing so when InspectFiles.visitFile()
is outside of the scope of the test class.
@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
@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"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.