tinonetic
tinonetic

Reputation: 8034

In an Espresso Test, how do I get a resource using ActivityTestScenario

I'm following the Android Code Lab for Espresso testing

It is outdated because it uses ActivityTestRule instead of the recommended ActivityScenarioRule

Outdated Code Snippets

The rule

@RunWith(AndroidJUnit4.class)
public class SpinnerSelectionTest {
@Rule
public ActivityTestRule mActivityRule = new ActivityTestRule<>(
                 MainActivity.class);

The test

@Test
public void iterateSpinnerItems() {
String[] myArray = 
     mActivityRule.getActivity().getResources()
     .getStringArray(R.array.labels_array);
}

Recommended Code

I have figured out the Rule

@RunWith(AndroidJUnit4.class)
public class SpinnerSelectionTest {

@Rule
public ActivityScenarioRule<EspressoSpinnerActivity> mActivityRule = new ActivityScenarioRule(
        EspressoSpinnerActivity.class);

The test

How to get the resource R.array.labels_array as it was done in the old code (above)?

Upvotes: 1

Views: 676

Answers (1)

tinonetic
tinonetic

Reputation: 8034

I found the solution. The key is to get the context using InstrumentationRegistry.getInstrumentation().getTargetContext()

Create a helper function to retrieve the string array resource values

private String[] getResourceArray(int id) {
    Context targetContext = 
        InstrumentationRegistry.getInstrumentation().getTargetContext();

    return targetContext.getResources().getStringArray(id);
}

Then in the @Test method, you can retrieve the array

 @Test
 public void iterateSpinnerItems() {
    String[] arr = getResourceArray(R.array.labels_array);

}

Upvotes: 4

Related Questions