Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we access context of an application in Robolectric?

Tags:

robolectric

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

You can use

RuntimeEnvironment.application

Add

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

And use:

private val app = ApplicationProvider.getApplicationContext()

Use this:

Robolectric.application

For the latest Robolectric 4.3 as of right now in 2019 `

ShadowApplication.getInstance()

` and

Roboletric.application

are both depricated. So I am using

Context context = RuntimeEnvironment.systemContext;

to get Context.


To get application context you must do the following:

  1. annotate @RunWith(RobolectricTestRunner.class)
  2. RuntimeEnvironment.application.getApplicationContext()

In some cases, you may need your app's context instead of the Robolectris default context. For example, if you want to get your package name. By default Robolectric will return you org.robolectric.default package name. To get your real package name do the following:

build.gradle

testImplementation 'org.robolectric:robolectric:4.2.1'

Your test class:

@RunWith(RobolectricTestRunner.class)
@Config( manifest="AndroidManifest.xml")
public class FooTest {

@Test
public void fooTestWithPackageName(){
    Context context = ApplicationProvider.getApplicationContext();
    System.out.println("My Real Package Name: " + context.getPackageName());
}

}

Make sure that in your Run/Debug Configurations Working directory is set to: $MODULE_DIR$ enter image description here enter image description here