How to run instrumentation tests for an android li

2019-07-11 05:45发布

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 library as a dependency, but it doesn't tell you what the wrapping applications activities will be called, which means you can't test it with the instrumentation classes (eg. http://developer.android.com/reference/android/test/ActivityTestCase.html). Since they need to know the activity in question, to initialize the super constructor.

Does anyone know the proper way to do this type of testing in android studio with gradle?

1条回答
Melony?
2楼-- · 2019-07-11 06:16

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.

public class ActivityTest extends ActivityInstrumentationTestCase2<TestActivity> {

public ActivityTest() {
    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>
    <activity
        android: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 ...

查看更多
登录 后发表回答