4

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);
    }

}
Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
  • 1
    ActivityTestRule replaced with [ActivityScenarioRule](https://developer.android.com/reference/androidx/test/rule/ActivityTestRule) . And there is no direct way of getting activity from `ActivityScenarioRule` which i can find [Except This](https://stackoverflow.com/a/54041319/4168607). So i guess `InstrumentationRegistry` is way to go IMO. – ADM Sep 08 '20 at 09:33
  • @ADM, ActivityTestRule exists and not deprecated if use @RunWith(AndroidJUnit4ClassRunner.class) annotation. – Yuliia Ashomok Sep 10 '20 at 11:05

1 Answers1

0

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

getApplicationContext().getString(resId)
Kuruchy
  • 1,330
  • 1
  • 14
  • 26