37

I have the following text in strings.xml resources file:

<string name="txt_to_assert">My Text</string>

Normally in a application code, to use this text and display it on screen, I'm doing the following:

getString(R.string.main_ent_mil_new_mileage);

At the moment, I'm trying to use this string resource in a UI test written with Espresso. I'm thinking of doing something like that:

String myTextFromResources = getString(R.string.main_ent_mil_new_mileage);
onView(allOf(withId(R.id.my_text_on_screen), withText(myTextFromResources))
    .check(matches(isDisplayed()));

However, getString(...) method cannot be used here.
Is there a way to get a text from strings.xml resource file and use it in a test written with Espresso?

klimos
  • 391
  • 1
  • 3
  • 5

4 Answers4

70

Use this function:

private String getResourceString(int id) {
    Context targetContext = InstrumentationRegistry.getTargetContext();
    return targetContext.getResources().getString(id);
}

You just have to call it with the id of the string and perform your action:

String myTextFromResources = getResourceString(R.string.main_ent_mil_new_mileage);
onView(allOf(withId(R.id.my_text_on_screen), withText(myTextFromResources))
    .check(matches(isDisplayed()));

*EDIT for new Espresso version:

With new version of Espresso, you should be able to call directly the string resource with a ViewMatcher. So first, I recommend to try directly this import

import static android.support.test.espresso.matcher.ViewMatchers.withText;

And then in the code:

withText(R.string.my_string_resource)
adalpari
  • 3,052
  • 20
  • 39
  • Nice to read that! you could accept my answer or vote me up mate ;) – adalpari Sep 13 '16 at 15:09
  • 1
    Voted up, but I'm getting messages that votes from users with less than 15 reputation are taken into account, but not shown publicly. – klimos Sep 14 '16 at 13:08
  • Your first method is still valid if we want to use equalToIgnoringCase from hamcrest. Example: onView(allOf(withText(equalToIgnoringCase(getResourceString(R.string.promos_activity_tab_store_))), isCompletelyDisplayed())).perform(click()); – Kunami Mar 08 '18 at 15:38
9

androidx.test.platform.app.InstrumentationRegistry is deprecated use androidx.test.core.app.ApplicationProvider

val targetContext: Context = ApplicationProvider.getApplicationContext()
val test: String =  targetContext.getResources().getString(R.string. my_text_on_screen)
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
8

Kotlin:

var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources
PSK
  • 583
  • 7
  • 15
1

If in case you have to append a text before the String resource, you will have to do it like this

val text=getApplicationContext<Context().getResources().getString(R.string.title_tenth_char) 

now that you have access to text append the string to that

Aniruddha K.M
  • 7,361
  • 3
  • 43
  • 52