J. Doe
J. Doe

Reputation: 291

How can I access a string resource from a test?

I have a project in android. I want to test it in junit. In the resources, insinide strings.xml I have a string array called labels_array. How can I access (get) this string array from a test method in junit?

In the test class I have

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

and


    @Test
    public void fooTest() {
        ActivityScenario scenario = mActivityRule.getScenario();
}

But How can I use these rule and method in order to acess the string array from inside the method fooTest?

Upvotes: 6

Views: 6469

Answers (3)

Martin Zeitler
Martin Zeitler

Reputation: 76809

It depends which source-set one intends to access. In order to load strings eg. from androidTest/res/strings.xml, one has to import class .test.R instead of class .R.

Then one can access the resources with .getContext() instead of .getTargetContext():

@RunWith(AndroidJUnit4.class)
public class SomeTest extends TestCase {
    String publicKey = null;
    @Before
    public void setupTest() {
        Context context = InstrumentationRegistry.getInstrumentation().getContext();
        this.publicKey = context.getString(R.string.some_public_key);
    }
    @Test
    ...
}

Upvotes: 0

Giorgio Antonioli
Giorgio Antonioli

Reputation: 16224

Since you want to obtain the real value of the string array, you can use:

final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
@ArrayRes final String[] labelsArray = context.getResources().getStringArray(R.array.labels_array);

Upvotes: 11

Serhat Levent Yavaş
Serhat Levent Yavaş

Reputation: 141

You can do this with mock.I think one of below links may be the solution to your request.

https://medium.com/android-testing-daily/unit-testing-xml-resources-7387447f9ef7

or

Unit test Android, getString from resource

Upvotes: 1

Related Questions