我有一个创建 ArrayList 的 CollectionObject 类。
public class CollectionObject {
private List<String> collectionObject;
public CollectionObject() {
collectionObject = new ArrayList<String>();
}
public List<String> getCollectionObject() {
return collectionObject;
}
public void add(final String stringToWrite) throws VerifyException {
collectionObject.add(stringToWrite);
}
}
还有另一个类接受类 CollectionObject 并使用它来将文件的内容写入类 CollectionObject。
public class ReaderFileWriterObjectService {
private BufferedReader bufferedReader;
private CollectionObject collectionObject;
private String line;
public CollectionObject getCollectionObjectAfterWritingFromAFile(final File file)
throws VerifyException, IOException {
collectionObject = new CollectionObject();
bufferedReader = new BufferedReader(new FileReader(file));
while ((line = bufferedReader.readLine()) != null) {
collectionObject.add(line);
}
bufferedReader.close();
return collectionObject;
}
如何测试和模拟 ReaderFileWriterObjectService 类的方法?
最佳答案
让我补充 @LouisWasserman's answer .
您无法测试依赖于 java.io.File
的 API;此类无法可靠地进行单元测试(即使它甚至不是 JDK 级别的 final
)。
但这与 Java 7 中出现的新文件系统 API 不同。
也称为 JSR 203,此 API 为提供“文件系统对象”的任何存储介质提供统一的 API。
短篇小说:
- “文件系统对象”通过此 API 中的路径具体化;
- 任何实现 JSR 203 的 JDK(即任何 Java 7+ 版本)都支持此 API;
- 要从默认
文件系统
上的资源获取路径,您可以使用Paths.get()
; - 但您不仅限于此。
简而言之,在您的 API 和 测试用例中,您应该使用Path
,而不是File
。如果您想测试与某些文件系统资源相关的任何内容,请使用 JDK 的 Files
类来测试 Path
实例。
并且您可以从您的主要的、基于磁盘的文件系统中创建FileSystem
。建议:使用this .
关于java - 如何对将文件作为参数的方法进行单元测试和模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743641/