在代码中创建File实例

时间:2014-02-22 17:51:07

标签: java unit-testing mockito

我有以下短代码片段,我尝试通过mockito进行单元测试

public String getExecutable()
{
    String result = executable;
    String ex = !hasExtension() ? executable + ".bat" : executable;
    File f = new File( dir, ex );
    if ( f.isFile() )
    {
        result = ex;
    }

    return result;
}

dir是类File的一个实例,它是通过构造函数提供给类的,所以没问题。只有这一行:

File f = new File( dir, ex );
if ( f.isFile() ) {
..
}

那么有没有机会通过Mockito模拟出来对它进行一些测试以便我可以控制isFile()的结果?有什么想法吗?

2 个答案:

答案 0 :(得分:2)

一个想法是将new File( dir, ex )提取到新的受保护方法并在测试期间覆盖它以返回模拟。

public class YourClass
{
    // ...

    public String getExecutable()
    {
        String result = executable;
        String ex = !hasExtension() ? executable + ".bat" : executable;
        File f = createFile( dir, ex );
        if ( f.isFile() )
        {
            result = ex;
        }

        return result;
    }

    @VisibleForTesting
    protected File createFile( String ex, String dir )
    {
        return new File( dir, ex );
    }
}

在执行测试之前:

@Test
public void shouldReturnExecutableFile()
{
    YourClass subject = new YourClass()
    {
        @Override
        protected File createFile( String ex, String dir )
        {
            // return a mock for File
        }
    };
}

这是迈克尔·费尔斯有效地使用遗产代码所提出的技巧之一。

答案 1 :(得分:2)

看起来dir是包含getExecutable()的类的成员变量?您可以将dir抽象为可能包含文件的内容:

class FileContainer {
    private final File dir;
    public FileContainer(File aDir) { dir = aDir; }
    public boolean contains(String aFile) {
        return new File(dir, aFile).isFile();
    }
}

让您的班级持有其中一个FileContainer个对象,并使用其contains()函数来测试文件。安排注入FileContainer的模拟版本进行测试。模拟版本将覆盖contains()并返回您想要的任何内容。