Shadowing getFilesDir() in Robolectric 3

我是研究僧i 提交于 2020-01-15 07:15:30

问题


I'd like to shadow Context.getFilesDir() in order to "virtualize" the filesystem my app is running in the test environment, but I can't find the right enclosing class to shadow.

I tried shadowing 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");
    }
}

but the method is never called, because apparently my app calls ContextWrapper.getFilesDir() which is not shadowed.

ContextWrapper is shadowed by Robolectric's ShadowContextWrapper. But even if I shadow ContextWrapper changing my class header as

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

my method isn't called too.

ShadowContext, the superclass of ShadowContextWrapper, is the shadow of Context, but I cannot find the concrete implementation of getFilesDir() that is called.

So my question is: is it possible to shadow getFilesDir() ? If so, how?


回答1:


I'm not really sure of what you're trying to do, but I have used the following to get the data directory on Robolectric tests:

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

From that I have been able to create dummy files for whatever purpose I need in a test. Hope it helps.



来源:https://stackoverflow.com/questions/31382189/shadowing-getfilesdir-in-robolectric-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!