I need to get resource from Android test (AndroidJUnit4ClassRunner). What is the recommended way and why?

String some_res_string = 
androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()
.getTargetContext().getString(R.string.some_res_string);

or

 String some_res_string = myActivityTestRule.getActivity() //Activity
                        .getString(R.string.some_res_string);

Full code

@RunWith(AndroidJUnit4ClassRunner.class)
public class MyActivityTest {

    @Rule
    public ActivityTestRule<MyActivity> myActivityTestRule =
            new ActivityTestRule<>(MyActivity.class, true, true);

    @Test
    public void test() throws Exception {
        String some_res_string = myActivityTestRule.getActivity() //Activity
                .getString(R.string.some_res_string);

        String some_res_string2 =
                androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()
                        .getTargetContext().getString(R.string.some_res_string);
    }

}
1

There are 1 answers

1
Kuruchy On

I think getting the Context from the InstrumentationRegistry directly is deprecated. The ApplicationProvider should be used instead.

getApplicationContext().getString(resId)