2

我希望能够使用 Mockery 在 java 中模拟 File 对象。我似乎我们可能无法为 java 中的文件创建接口。这可能吗?

编辑:

我需要在 Indexer Class 中测试 indexDoc 函数。

@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  
}

Indexer 类中的索引文档功能

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);
  }
}
4

3 回答 3

3

不要模拟文件系统。我们在早期尝试这样做,它使我们无法使用测试来指导设计。

快速浏览一下您的代码,发生了两件事,一是文件导航,二是 html 剥离。也许一种选择是引入一个 html 剥离对象(作为协作者传入)并模拟它,然后针对真实文件系统中的示例编写测试。

于 2011-02-06T09:44:08.700 回答
1

Jmock 可以模拟具体的类。做就是了

Mockery context = new Mockery();

context.setImposteriser(ClassImposteriser.INSTANCE);
于 2011-02-04T18:02:49.137 回答
0

您遇到的问题是确切的原因,应该使用抽象而不是具体的类。

于 2011-02-06T10:01:46.657 回答