在 Robolectric 3 中隐藏 getFilesDir()

Shadowing getFilesDir() in Robolectric 3

我想隐藏 Context.getFilesDir() 以便 "virtualize" 我的应用程序在测试环境中 运行 的文件系统,但我找不到正确的封闭 class 到阴影。

我试过跟踪 Context:

@Implements(Context.class)
public class MyShadow extends ShadowContext {
    private File testRoot;

    public MyShadow() {
        testRoot = new File(FileUtils.getTempDirectory(), "androidTestRoot-" + System.currentTimeMillis());
    }

    @Implementation
    public File getFilesDir() {
        return new File(testRoot, "data/data/com.myapp/files");
    }
}

但该方法从未被调用,因为显然我的应用程序调用了 ContextWrapper.getFilesDir(),它没有被隐藏。

ContextWrapper 被 Robolectric 的 ShadowContextWrapper 遮挡。但即使我影子 ContextWrapper 改变我的 class header 为

@Implements(ContextWrapper.class)
public class MyShadow extends ShadowContextWrapper 

我的方法也没有被调用。

ShadowContext,ShadowContextWrapper的superclass,是Context的影子,但是找不到getFilesDir()的具体实现打电话。

所以我的问题是:是否可以隐藏 getFilesDir() ?如果是,怎么做?

我不太确定你要做什么,但我使用以下方法在 Robolectric 测试中获取数据目录:

RuntimeEnvironment.application.getApplicationContext().getFilesDir();

从那以后,我已经能够为我在测试中需要的任何目的创建虚拟文件。希望对你有帮助。