Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso - assert text on screen against string in resources

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?

like image 353
klimos Avatar asked Sep 12 '16 15:09

klimos


People also ask

How do I get Textview espresso from text?

The basic idea is to use a method with an internal ViewAction that retrieves the text in its perform method. Anonymous classes can only access final fields, so we cannot just let it set a local variable of getText() , but instead an array of String is used to get the string out of the ViewAction .

What is espresso Kotlin?

Espresso is a user interface-testing framework for testing android application developed in Java / Kotlin language using Android SDK. Therefore, espresso's only requirement is to develop the application using Android SDK in either Java or Kotlin and it is advised to have the latest Android Studio.


2 Answers

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) 
like image 101
adalpari Avatar answered Sep 19 '22 08:09

adalpari


Kotlin:

var resources: Resources = InstrumentationRegistry.getInstrumentation().targetContext.resources 
like image 32
PSK Avatar answered Sep 22 '22 08:09

PSK