2013-06-06 27 views
1

下測試單位如下:是否有可能通過使用JMockit來嘲諷局部變量?

@Component(value = "UnitUnderTest") 
public class UnitUnderTest { 

    @Resource(name = "propertiesManager") 
    private PropertiesManager prop; 

    public List<String> retrieveItems() { 
     List<String> list = new ArrayList<String>(); 
     String basehome = prop.get("FileBase"); 
     if (StringUtils.isBlank(basehome)) { 
      throw new NullPointerException("basehome must not be null or empty."); 
     } 


     File target = new File(basehome, "target"); 
     String targetAbsPath = target.getAbsolutePath(); 
     File[] files = FileUtils.FolderFinder(targetAbsPath, "test");//A utility that search all the directories under targetAbsPath, and the directory name mush match a prefix "test" 

     for (File file : files) { 
      list.add(file.getName()); 
     } 
     return list; 
    } 
} 

測試情況如下:

public class TestExample { 
    @Tested 
    UnitUnderTest unit; 
    @Injectable 
    PropertiesManager prop; 

    /** 
    * 
    * 
    */ 
    @Test 
    public void retrieveItems_test(@NonStrict final File target,@Mocked FileUtils util){ 
     new Expectations(){ 
      { 
       prop.get("FileBase"); 
       result="home"; 
       target.getAbsolutePath(); 
       result="absolute"; 
       FileUtils.FolderFinder("absolute", "test"); 
       result=new File[]{new File("file1")}; 
      } 
     }; 
     List<String> retrieveItems = logic.retrieveItems(); 
     assertSame(1, retrieveItems.size()); 
    } 
} 

它的失敗。 retrieveItems的實際返回值是空的。我發現「FileUtils.FolderFinder(targetAbsPath,」test「)」總是返回一個空的File []。這真的很奇怪。

這可能是因爲我嘲笑文件實例「目標」以及。它工作正常,如果我只嘲笑靜態方法FileUtils.FolderFinder。

有誰知道問題是什麼?是否有可能嘲笑一個局部變量實例像我這裏所需要的?比如這個目標實例?

非常感謝!

回答

2

問題是我應該定義我想要模擬的方法。

@Test 
    public void retrieveItems_test(@Mocked(methods={"getAbsolutePath"}) final File target,@Mocked FileUtils util){ 
     new Expectations(){ 
      { 
       prop.get("FileBase"); 
       result="home"; 
       target.getAbsolutePath(); 
       result="absolute"; 
       FileUtils.FolderFinder("absolute", "test"); 
       result=new File[]{new File("file1")}; 
      } 
     }; 
     List<String> retrieveItems = logic.retrieveItems(); 
     assertSame(1, retrieveItems.size()); 
    } 

這樣會好的。

+1

是的,之前整個'File'類被嘲笑,所以像'file.getName()'這樣的調用也受到了影響。只嘲笑相關的方法(可以簡化爲'@Mocked(「getAbsolutePath」)'),但我建議不要模擬'File',因爲在這個測試中不需要它。 –

+0

感謝您的解釋。如你所說,這裏真的沒有必要模擬文件。 ^^,很高興知道這一點。 – Howard