Accessing application context from TestSuite in Setup() before calling getActivity()

前端 未结 6 906
太阳男子
太阳男子 2020-12-08 09:42

I have an Activity that pulls an object from an Application extended class (application context) from within the OnCreate() method.

相关标签:
6条回答
  • 2020-12-08 10:13

    Ok, this issue is resolved. To get access to the context before getActivity() has been called you need to call this function:

    Context context = this.getInstrumentation().getTargetContext().getApplicationContext();
    
    0 讨论(0)
  • 2020-12-08 10:19

    You can get the application context using the androidx.test.core.app.ApplicationProvider.getApplicationContext(). Cast that to your application and it should be the right context.

    0 讨论(0)
  • 2020-12-08 10:20

    In kotlin val context = InstrumentationRegistry.getInstrumentation().context worked for me.

    0 讨论(0)
  • 2020-12-08 10:22

    You can call the static method for the Context:

    Context context = InstrumentationRegistry.getTargetContext();
    

    More details can be found here: https://developer.android.com/training/testing/integration-testing/index.html

    0 讨论(0)
  • 2020-12-08 10:27

    Always use this.getInstrumentation().getTargetContext() to access the context of the application.

    this.getInstrumentation().getTargetContext().getApplicationContext() is not same as this.getInstrumentation().getTargetContext()

    I was running the automation in 4.0.X versions and most of the time getApplicationContext() was returning null context.

    0 讨论(0)
  • 2020-12-08 10:28

    With the newer UI testing framework getInstrumentation() is no longer available. One way to get hold of the Application object is to cast the application Context:

    Application app = 
            (Application) InstrumentationRegistry
                    .getTargetContext()
                    .getApplicationContext();
    
    0 讨论(0)
提交回复
热议问题