Get context of test project in Android junit test case

后端 未结 10 2189
闹比i
闹比i 2020-12-02 12:58

Does anyone know how can you get the context of the Test project in Android junit test case (extends AndroidTestCase).

Note: The test is NOT instru

相关标签:
10条回答
  • 2020-12-02 13:26

    For those encountering these problems while creating automated tests, you've gotta do this :

        Context instrumentationContext;
    
        @Before
        public void method() {
    
            instrumentationContext = InstrumentationRegistry.getInstrumentation().getContext();
    
            MultiDex.install(instrumentationContext);
        }
    
    0 讨论(0)
  • 2020-12-02 13:27

    Update: AndroidTestCase This class was deprecated in API level 24. Use InstrumentationRegistry instead. New tests should be written using the Android Testing Support Library. Link to announcement

    You should extend from AndroidTestCase instead of TestCase.

    AndroidTestCase Class Overview
    Extend this if you need to access Resources or other things that depend on Activity Context.

    AndroidTestCase - Android Developers

    0 讨论(0)
  • 2020-12-02 13:28

    The other answers are outdated. Right now every time that you extend AndroidTestCase, there is mContext Context object that you can use.

    0 讨论(0)
  • 2020-12-02 13:34

    This is to correct way to get the Context. Other methods are already deprecated

    import androidx.test.platform.app.InstrumentationRegistry
    
    InstrumentationRegistry.getInstrumentation().context
    
    0 讨论(0)
提交回复
热议问题