Android JUnit4 Testing - Where to get Context from?

前端 未结 1 1474
感动是毒
感动是毒 2020-12-09 08:53

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 provi

相关标签:
1条回答
  • 2020-12-09 09:32

    As described here: https://code.google.com/p/android-test-kit/wiki/AndroidJUnitRunnerUserGuide Use the InstrumentationRegistry to obtain the context.

    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()

    For example:

    @RunWith(AndroidJUnit4.class)
    public class SqliteTest {
    
        Context mMockContext;
    
        @Before
        public void setUp() {
            mMockContext = new RenamingDelegatingContext(InstrumentationRegistry.getTargetContext(), "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.

    0 讨论(0)
提交回复
热议问题