Common-VFS allows the developers to span the following file systems and formats...
- Local Files
- HTTP and HTTPS
- Temporary Files
- Zip, Jar and Tar (uncompressed, tgz or tbz2)
- gzip and bzip2
First, I will create an interface named PACFileHandler. The interface will define the contract for any implementation of the PACFileHandler.
The mock class of the implementation will implement PACFileHandler and will look like this...
The following code from the mock open() method will initialize the commons-VFS File System Manager. Notice, how the file name is referenced. The path to our virtual file will start with "ram://". Other tests could easily be created using the formats discussed earlier, but in this case we will be creating the virtual file in the ram://
FileSystemManager fsManager = VFS.getManager();
String fileString = "ram://" + fileName;
jarFile = fsManager.resolveFile(fileString);
The above mock class will be passed into a PACFile object which will read and write the contents of the file using the PACFileHandlerMock class. In runtime the PACFile object will reference the PACFileHandlerImpl, and our mock object should imitate a true File object without many differences.
Last, let's create a JUnit 4 test case called PACFileTest...
Next run the previous unit test...
Mar 25, 2009 11:45:58 PM org.apache.commons.vfs.VfsLog info
INFO: Using "/tmp/vfs_cache" as temporary files store.
The previous code will create the mock PACFileHandler, and after create and write a virtual file to memory with the contents
"Four score and seven years ago".
The file will then be read back and regurgitated back into the unit test assertion for a final check. Many permutations of this example can be made for test cases. Many of the commons-VFS library formats outside of ram:// can be used instead (ftp, http, smb, etc.)