简体   繁体   English

Jmock Mockery,模拟文件系统对象

[英]Jmock Mockery, mocking a file system object

I want to be able to mock the File object in java using Mockery. 我希望能够使用Mockery模拟Java中的File对象。 I seems like we may not be able to create an interface for the File in java. 我似乎无法在Java中为File创建接口。 Is this possible? 这可能吗?

EDIT: 编辑:

I need to test the indexDoc function in Indexer Class. 我需要测试Indexer类中的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  
}

Index Docs function in Indexer class 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);
  }
}

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. 快速查看您的代码,有两件事正在进行,一是文件导航,二是html剥离。 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. 也许一种选择是引入html剥离对象(作为协作者传入)并对其进行模拟,然后针对实际文件系统中的示例编写测试。

Jmock can mock concrete classes. Jmock可以模拟具体的类。 Just do 做就是了

Mockery context = new Mockery();

context.setImposteriser(ClassImposteriser.INSTANCE);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM