java – 如何对文件作为参数的方法进行单元测试和模拟
我有一个类CollectionObject创建一个ArrayList.
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级别的最终版). 但是新的文件系统API并不是这种情况,它出现在Java 7中. 此API也称为JSR 203,为提供“文件系统对象”的任何存储介质提供统一的API. 短篇故事: >“文件系统对象”由此API中的Path实现; 简而言之,在您的API和测试用例中,您应该使用Path而不是File.如果要测试与某些文件系统资源相关的任何内容,请使用JDK的Files类来测试Path实例. 您可以从主要的基于磁盘的文件系统中创建FileSystems.建议:使用this. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |