Reputation: 3484
I want to be able to mock the File object in java using Mockery. I seems like we may not be able to create an interface for the File in java. Is this possible?
EDIT:
I need to test the indexDoc function in Indexer Class.
@Test
public void testindexDocs()
{
final File f = mockFile.mock(File.class);
File file = new File("test");
mockFile.setImposteriser(ClassImposteriser.INSTANCE);
final String[] files = {
"C:\\test\\",
"C:\\test\\test1.html",
"C:\\test\\test2",
"C:\\test\\test3.html"};
mockFile.checking(new Expectations(){
{
one(f).list();will(returnValue(files));
}
});
//TODO test if list() how many time i have called
//Document doc = HTMLDocument.Document(file); in function indexDocs
}
Index Docs function in Indexer class
private static void indexDocs(File file) throws Exception{
//Check for file to be a directory or file to be indexed look for html files and add to document
if(file.isDirectory()){
String[] files = file.list();
Arrays.sort(files);
for (int i = 0; i < files.length; i++) // recursively index them
indexDocs(new File(file, files[i]));
} else if(file.getPath().endsWith(".html") || file.getPath().endsWith("htm")){
// Get the document from HTMLDocument class which takes care of stripping of HTML tag, get the path
// of HTML file and title of HTML document.
Document doc = HTMLDocument.Document(file);
// TODO Get the book of HTML, it can be a part of HTML document class.
writer.addDocument(doc);
}
}
Upvotes: 2
Views: 2078
Reputation: 18266
The problems your having are the exact reason, one should use abstractions rather than concrete classes.
Upvotes: 0
Reputation: 2707
Don't mock the file system. We tried to do this in the early days and it diverted us from using tests to guide the design.
From a quick look at your code, there are two things going on, one is file navigation, the other is html stripping. Perhaps one option would be to introduce a html stripping object (passed in as a collaborator) and mock that, then write tests against examples in a real file system.
Upvotes: 3
Reputation: 19
Jmock can mock concrete classes. Just do
Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE);
Upvotes: 1