Android JUnit4测试 - 如何获取上下文?

26
我需要使用SQLite来构建一个应用程序,现在我想编写单元测试。这些单元测试应该测试我的类SQLiteBridgeSQLiteBridge为每个Model的子类提供DAO。
现在我遇到了一个问题,我需要一个上下文来创建我的SQLiteBridgeSQLiteBridge在系统上创建和处理SQLite数据库。
从哪里获取Context对象?
我的设置如下(所以我正在使用Junit4 [感谢上帝]):http://tools.android.com/tech-docs/unit-testing-support 编辑:我希望有一种方法可以像旧的AndroidTestCase一样扩展而不失去Junit4。 :)
2个回答

55

如此描述:https://code.google.com/p/android-test-kit/wiki/AndroidJUnitRunnerUserGuide 使用InstrumentationRegistry获取上下文。

但是,如果您直接调用InstrumentationRegistry.getContext(),可能会出现打开数据库的异常。我认为这是因为getContext()返回的上下文指向的是测试工具的上下文,而不是您的应用程序/单元测试的上下文。相反,请使用InstrumentationRegistry.getInstrumentation().getTargetContext()

例如:

@RunWith(AndroidJUnit4.class)
public class SqliteTest {

    Context mMockContext;

    @Before
    public void setUp() {
        mMockContext = new RenamingDelegatingContext(InstrumentationRegistry.getTargetContext(), "test_");
    }
}

RenamingDelegatingContext仅仅是在文件/数据库名称前缀中添加test_,以防止您覆盖可能存在于同一模拟器中的数据。


我刚试了一下,它可以工作!我想我会使用Robolectric..但还是谢谢你提供的解决方案! :) - Dominic Fuchs
1
我已经尝试过这个方法并且它有效,但是前缀被忽略了,因此在测试中使用的是“真实”的数据库。有任何想法为什么会发生这种情况吗? - moarCoffee
5
InstrumentationRegistry无法解析为符号。 - Kaloyan Roussev
1
InstrumentationRegistry.getTargetContext(); - Benny

4

jUnit 4(以及其他版本的jUnit)和androidx使用:

ApplicationProvider.getApplicationContext();

参见:Android文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接