How can we access context of an application in Robolectric?

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

    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
    

提交回复
热议问题