I have an Activity
that pulls an object from an Application
extended class (application context) from within the OnCreate()
method.
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();
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.
In kotlin val context = InstrumentationRegistry.getInstrumentation().context
worked for me.
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
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.
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();