How can we access context of an application in Robolectric?

后端 未结 14 1462
既然无缘
既然无缘 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:29

    It is safer to use Robolectric.getShadowApplication() instead of using Robolectric.application directly.

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

    Ok, so I know many others said this answer before and might already outdated

        when(mockApplication.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
        when(mockApplication.getFilesDir()).thenReturn(RuntimeEnvironment.application.getFilesDir());
    
        sharedPref = RuntimeEnvironment.application.getSharedPreferences(KEY_MY_PREF, Context.MODE_PRIVATE);
        sut = new BundleManagerImpl(mockApplication,
                processHtmlBundle, resultListener, sharedPref);
    

    I got null, because the when() part was AFTER the sut initialization. It might help some of you.

    also I have the

    @RunWith(CustomRobolectricTestRunner.class)
    @Config(constants = BuildConfig.class)
    

    at the beginning of the class

    Also

     when(mockApplication.getApplicationContext()).thenReturn(RuntimeEnvironment.application.getApplicationContext()); works
    
    0 讨论(0)
提交回复
热议问题