[英]Jmock Mockery, mocking a file system object
我希望能夠使用Mockery模擬Java中的File對象。 我似乎無法在Java中為File創建接口。 這可能嗎?
編輯:
我需要測試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
}
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);
}
}
不要嘲笑文件系統。 我們在早期嘗試這樣做,這使我們無法使用測試來指導設計。
快速查看您的代碼,有兩件事正在進行,一是文件導航,二是html剝離。 也許一種選擇是引入html剝離對象(作為協作者傳入)並對其進行模擬,然后針對實際文件系統中的示例編寫測試。
Jmock可以模擬具體的類。 做就是了
Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE);
您遇到的問題是確切的原因,應該使用抽象而不是具體的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.