简体   繁体   中英

Get resource from Android test: InstrumentationRegistry.getInstrumentation().getTargetContext() VS myActivityTestRule.getActivity()

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

}

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

getApplicationContext().getString(resId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM