用于使其更易测试的接口

时间:2012-10-22 10:41:34

标签: java unit-testing

我正在查看android源代码,我发现了这段代码。

/**
 * Interface used in {@link #createUniqueFile} instead of {@link File#createNewFile()} to make
 * it testable.
 */
/* package */ interface NewFileCreator {
    public static final NewFileCreator DEFAULT = new NewFileCreator() {
                @Override public boolean createNewFile(File f) throws IOException {
                    return f.createNewFile();
                }
    };
    public boolean createNewFile(File f) throws IOException ;
}

它如何更可测试?任何人都可以将我重定向到我能看到更多例子的地方吗?

2 个答案:

答案 0 :(得分:4)

原因在于,在测试中,您可以使用不同的实现替换NewFileCreator,无论它在何处使用 - 例如,只将数据保存在内存中。

这意味着您可以测试使用它的任何逻辑,而不必担心确保存在真正的文件系统并且它处于合适的状态。

答案 1 :(得分:1)

我认为“使其可测试”这一陈述指的是似乎使用createUniqueFile实例的方法NewFileCreator。该方法应该在隔离中更好地测试,因为模拟NewFileCreator比从标准Ja​​va API模拟File更容易。还可以提供NewFileCreator的不同实现,以便进行不会弄乱文件系统的测试。

相关问题