Skip to content Skip to sidebar Skip to footer

How To Run Instrumentation Tests For An Android Library In Android Studio?

The documentation (http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Testing-Android-Libraries) says that it will just auto-generate the app and run with the libra

Solution 1:

Alright, I've got one possible solution. Whether or not it is the "right" approach I'll see what people say.

In theory nothing stops me creating a "TestActivity.java" class somewhere under

/src/androidTest/java/com....bananas/TestActivity.java

And this is true. You can reference this within a potential ActivityTest.java sitting under androidTest.

publicclassActivityTestextendsActivityInstrumentationTestCase2<TestActivity> {

publicActivityTest() {
    super(TestActivity.class);
}
...

There is however one glitch/catch. IF the TestActivity needs to reference any strings/constants (eg. res/layout/activity_test.xml) they cannot be under /src/androidTest/res/layout/. This folder is inexplicably ignored during build. Even though it is listed as the res source folder for the gradle build (I checked via gradle dumping (println android.sourceSets.androidTest.dump()), the contents are not found when going to build & run the tests...and you get:

No resource found that matches the given name ...

So, this means that you can test libs with custom activities as you please, without having to spin up a full separate test app, but you get some extra clutter in your res folder for the library. (though these could be manually excluded from the final .aar).

It would be nice if someone could explain this odd gotcha, or prove me wrong, but otherwise this works. :)


Edit/Update

One thing to add in, is to make sure that the AndroidManifest.xml under /src/androidTest contains something like:

<application><activityandroid:name=".TestActivity"android:label="@string/title_activity_test" ></activity></application>

getActivity() within the ActivityInstrumentationTestCase2 will throw an error if omitted:java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN ...

Post a Comment for "How To Run Instrumentation Tests For An Android Library In Android Studio?"