Android JUnit4测试-从何处获取上下文?
我必须使用sqlite来构建一个应用程序.现在,我要编写单元测试.这些单元测试应该测试我的课程SQLiteBridge
. SQLiteBridge
为Model的每个子类提供DAO.
I have to build an app with sqlite usage. Now I want to write my unit tests. These unit tests should test my class SQLiteBridge
. SQLiteBridge
provides DAOs for every child class of Model.
现在我遇到一个问题,我需要一个上下文来创建我的SQLiteBridge
. SQLiteBridge
在系统上创建和处理SQLite数据库.
Now I got the problem that I need a context to create my SQLiteBridge
. SQLiteBridge
creates and handles a SQLite database on the system..
从哪里获取上下文对象?
Where to get the Context-Object from?
我的设置就像这里(所以我正在使用Junit4 [感谢上帝]): http://tools.android.com/tech-docs/unit-testing-support
My setup is like here (so I'm using Junit4 [thanks god]): http://tools.android.com/tech-docs/unit-testing-support
我希望有一种像旧版AndroidTestCase
那样的扩展方式而不会丢失Junit4. :)
I hope there is a way like the old AndroidTestCase
to extend without losing Junit4. :)
如此处所述: https ://code.google.com/p/android-test-kit/wiki/AndroidJUnitRunnerUserGuide 使用InstrumentationRegistry获取上下文.
As described here: https://code.google.com/p/android-test-kit/wiki/AndroidJUnitRunnerUserGuide Use the InstrumentationRegistry to obtain the context.
但是,如果直接调用InstrumentationRegistry.getContext()
,则打开数据库可能会出现异常.我相信这是因为getContext()返回的上下文指向工具的上下文,而不是应用程序/单元测试的上下文.而是使用InstrumentationRegistry.getInstrumentation().getTargetContext()
However if you call InstrumentationRegistry.getContext()
directly you may get an exception opening your database. I believe this is because the context returned by getContext() points to the instrumentation's context rather than that of your application / unit test. Instead use InstrumentationRegistry.getInstrumentation().getTargetContext()
例如:
@RunWith(AndroidJUnit4.class)
public class SqliteTest {
Context mMockContext;
@Before
public void setUp() {
mMockContext = new RenamingDelegatingContext(InstrumentationRegistry.getTargetContext(), "test_");
}
}
RenamingDelegatingContext只是在文件/数据库名称的前面加上test_前缀,以防止您覆盖同一模拟器中可能拥有的数据.
The RenamingDelegatingContext simply prefixes the file/database names with test_ to prevent you from overwriting data that you may have in the same simulator.