本文介绍了JUnit测试扫描文件夹类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写几个测试,但是从较高的角度来看,每个测试都应在目录结构中填充一些文件.我至少会测试每种情况:
I want write several tests, but from a high level each of them should populate a directory structure with some files. I'd test each of these cases at least:
一个具有通过过滤器的文件的文件夹.
单个文件夹中包含未通过过滤器的文件.
嵌套的文件夹,每个文件夹中都有一个文件.
A single folder with a file that passes the filter.
A single folder with a file that does NOT pass the filter.
A nested folder with a file in each.
代码:
class FolderScan implements Runnable {
private String path;
private BlockingQueue<File> queue;
private CountDownLatch latch;
private File endOfWorkFile;
private List<Checker> checkers;
FolderScan(String path, BlockingQueue<File> queue, CountDownLatch latch,
File endOfWorkFile) {
this.path = path;
this.queue = queue;
this.latch = latch;
this.endOfWorkFile = endOfWorkFile;
checkers = new ArrayList<Checker>(Arrays.asList(new ExtentionsCheker(),
new ProbeContentTypeCheker(), new CharsetDetector()));
}
public FolderScan() {
}
@Override
public void run() {
findFiles(path);
queue.add(endOfWorkFile);
latch.countDown();
}
private void findFiles(String path) {
boolean checksPassed = true;
File root;
try {
root = new File(path);
File[] list = root.listFiles();
for (File currentFile : list) {
if (currentFile.isDirectory()) {
findFiles(currentFile.getAbsolutePath());
} else {
for (Checker currentChecker : checkers) {
if (!currentChecker.check(currentFile)) {
checksPassed = false;
break;
}
}
if (checksPassed)
queue.put(currentFile);
}
}
} catch (InterruptedException | RuntimeException e) {
System.out.println("Wrong input !!!");
e.printStackTrace();
}
}
}
问题:
- 如何在每个文件夹中创建文件?
- 证明队列包含您期望的文件对象?
- 队列中的最后一个元素是触发"文件?
- How to create files into each folder?
- To prove that queue containsthe File objects that you expect?
- The last element in queue is the'trigger' File?
推荐答案
- 提取文件IO并使用模拟的存储库进行测试.这意味着您将在其他地方拥有IO,并可能希望使用以下内容进行测试.
- 使用 JUnit规则使用测试文件夹,您可以创建与测试匹配的文件.
- Extract the file IO and use a mocked repository for the tests. This means that you will have the IO somewhere else and may wish to use the below to test that.
- A temp folder using the JUnit rule With a test folder you create the files to match the test.
我相信
.equals可以很好地用于File对象.
.equals works well for File objects I believe.
我会通过阻止程序,以便可以通过始终通过"和始终失败"阻止程序.
I'd pass in the blockers so I can pass in an "Always Pass" and "Always Fail" blocker.
public class TestFolderScan {
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test
public void whenASingleFolderWithAFileThatPassesTheFilterThenItExistsInTheQueue() {
File expectedFile = folder.newFile("file.txt");
File endOfWorkFile = new File("EOW");
Queue queue = ...;
FolderScan subject = new FolderScan(folder.getRoot(), queue, new AllwaysPassesBlocker(),...);
subject.run();
expected = new Queue(expectedFile, endOfWorkFile);
assertEquals(queue, expected);
}
}
这篇关于JUnit测试扫描文件夹类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!