gpt4 book ai didi

android - 在 Robolectric 3 中隐藏 getFilesDir()

转载 作者:行者123 更新时间:2023-11-29 00:09:20 25 4
gpt4 key购买 nike

我想隐藏 Context.getFilesDir() 以便“虚拟化”我的应用程序在测试环境中运行的文件系统,但我找不到合适的封闭类来隐藏.

我尝试隐藏 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 将我的类头更改为

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

我的方法也没有被调用。

ShadowContextShadowContextWrapper的父类,是Context的影子,但是找不到getFilesDir( ) 被调用。

所以我的问题是:是否可以屏蔽 getFilesDir() ?如果是,怎么办?

最佳答案

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

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

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

关于android - 在 Robolectric 3 中隐藏 getFilesDir(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31382189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com