Java – how to unit test and simulate methods with files as parameters

I have a collectionobject class to create an 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);
    }
}

There is another class that accepts the class collectionobject and uses it to write the contents of the file to the class 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;
    }

How to test and simulate the method of class readerfilewriterobjectservice?

Solution

Let me add @ Louis Wasserman's answer

You cannot test dependencies on Java io. File API; This class can't reliably unit test (even if it's not even the final version of the JDK level)

But this is not the case with the new file system API, which appears in Java 7

This API, also known as JSR 203, provides a unified API for any storage medium that provides "file system objects"

Short story:

>"File system object" is implemented by path in this API; > Any JDK implementing JSR 203 (i.e. any Java 7 version) supports this API; > To get a path from a resource on the default file system, you can use paths get(); > But you're not limited to that

In short, in your API and test cases, you should use path instead of file If you want to test anything related to some file system resources, use the files class of JDK to test the path instance

You can create filesystems from the primary disk based file system Suggestion: use this

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>