How can we access context of an application in Robolectric?

Actually, I need to get a response of an API call, for that I required Context.


Solution 1:

Update.

Just use for version 1.x and 2.x:

Robolectric.application;

And for version 3.x:

RuntimeEnvironment.application;

And for version 4.x:

  • add to your build.gradle file:

    testImplementation 'androidx.test:core:1.0.0'
    
  • retrieve the context with:

    ApplicationProvider.getApplicationContext()
    

Solution 2:

You can use

RuntimeEnvironment.application

Solution 3:

Add

testImplementation "androidx.test:core-ktx:${deps.testrunner}"

And use:

private val app = ApplicationProvider.getApplicationContext()

Solution 4:

Use this:

Robolectric.application