【问题标题】:Jmock Mockery, mocking a file system objectJmock Mockery,模拟文件系统对象
【发布时间】:2015-04-16 08:49:45
【问题描述】:

我希望能够使用 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类中的Index Docs函数

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

【问题讨论】:

    标签: java junit junit4 jmock


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      Jmock 可以模拟具体的类。做吧

      Mockery context = new Mockery();
      
      context.setImposteriser(ClassImposteriser.INSTANCE);
      

      【讨论】:

      • 我已经编辑了这个问题..以便您更好地理解我的担忧
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 1970-01-01
        • 2012-11-08
        相关资源
        最近更新 更多