问题
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