Question

Unit under test as following:

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

Test case as below:

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

It's failed. The actual ressult of retrieveItems is empty. I found that "FileUtils.FolderFinder(targetAbsPath, "test")" is always return an empty File[]. That's really weird.

It probably because i mocked File instance "target" as well. It works fine if i only mocking the static method FileUtils.FolderFinder.

Does anyone know what the problem is? And is it possible to mock a local variable instance like i required here? Such as this target instance?

Thanks a lot!

Was it helpful?

Solution

The problem is that i should define which method i want to mock.

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

This will be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top