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:
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$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With