Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing resources for Android UI Automator tests

I'm working on a set of tests using UI Automator on Android. I have it working, but my current tests are made with lots of string literals.

The string literals were fine when I was just trying to get things to work in the first place, but they will be bad going forward. If the app is changed, the string literals will need to be changed to match. Also, it's stupid that my tests would have to be completely redone to test localized builds in other languages.

The app itself has all strings stored in resources. Every string has an invariant identifier... here's an example:

<string name="more_options">More options</string>

The app code will always use the name more_options to look up the string resource, rather than hard-coding "More options" into the code.

So what I want is to import all the string resources, store them in some kind of map object, and then in my UI Automator test code use something like m.get("more_options") rather than a literal string "More options" as I do now.

Whatever I do, I want it to just be part of the JAR file that gets built and pushed to the device to run the tests. I don't want to, for example, push the XML string resource files to the device and try to read them at test runtime. I want to have the data built in when the JAR file is built.

I looked at the files produced by building the app, and the names like more_options are just set to integers. These must be indexes or pointers into a store of resources, but I'm not sure how I could copy that store into my UI Automator project and get it connected up; in an Android app you use a Context object to access resources, and a UI Automator JAR file doesn't have a Context.

This has to be a common problem, and people must have solved it already, but my Google searches haven't found any discussions of how people are solving this.

If I don't get any advice, I'm going to write a Python script that imports the XML file and writes a Java file that has a function that builds the map I need, then call that from my UI Automator test programs. (I have a Python script that runs the sequence of command-line tools to kick of a UI Automator test, anyway... I don't mind making that do more work.) But I figure there should be a pure-Java solution for this, probably one that involves grabbing the already-compiled files out of the application's source directory.

like image 851
steveha Avatar asked Dec 21 '22 02:12

steveha


2 Answers

You can get context:

val context = InstrumentationRegistry.getTargetContext()

and then in your tests:

context.getString(R.string.more_options)
like image 84
karla Avatar answered Dec 22 '22 14:12

karla


I usually target a UI element through a resource ID. Those are pretty static. Am I missing something?

like image 20
Anthony Chuinard Avatar answered Dec 22 '22 16:12

Anthony Chuinard