How can we access context of an application in Robolectric?

后端 未结 14 1461
既然无缘
既然无缘 2020-12-05 03:32

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

相关标签:
14条回答
  • 2020-12-05 04:04

    You can use

    RuntimeEnvironment.application
    
    0 讨论(0)
  • 2020-12-05 04:04

    Add

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

    And use:

    private val app = ApplicationProvider.getApplicationContext()
    
    0 讨论(0)
  • 2020-12-05 04:08

    To get application context you must do the following:

    1. annotate @RunWith(RobolectricTestRunner.class)
    2. RuntimeEnvironment.application.getApplicationContext()
    0 讨论(0)
  • 2020-12-05 04:08

    Agree with answers of @EugenMartynov and @rds ....

    A quick example can be found at Volley-Marshmallow-Release

    in NetworkImageViewTest.java

    // mNIV = new NetworkImageView(Robolectric.application); mNIV = new NetworkImageView(RuntimeEnvironment.application);

    Volley link is available https://android.googlesource.com/platform/frameworks/volley/+/marshmallow-release

    you have to add dependencies in volley module in android studio as :

    dependencies { testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.10.19' testCompile 'org.robolectric:robolectric:3.1.2' }

    0 讨论(0)
  • 2020-12-05 04:09

    This works for me with Robolectric 3.5.1: ShadowApplication.getInstance().applicationContext

    0 讨论(0)
  • 2020-12-05 04:11

    Use this:

    Robolectric.application
    
    0 讨论(0)
提交回复
热议问题