被测单元如下:
@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,它就可以正常工作。
有谁知道问题是什么?是否可以像我在这里需要的那样模拟局部变量实例?比如这个目标实例?
非常感谢!