Unit tests with Android Studio and Gradle?

前端 未结 2 1064
后悔当初
后悔当初 2020-12-31 12:11

How can I add unit tests to my Android projects in Android Studio (IntelliJ) easily?

To be more exact: I want to add a folder with test code (JUnit 4) and execute th

相关标签:
2条回答
  • 2020-12-31 12:43

    I have spent the past weeks (also) on that. Actually, on that on steroids, since I also had to put Robolectric into the pot.

    Short answer: unless I confuse that error with something else, I think you are trying to run unit tests with the Android testrunner.

    Long answer: I ended up with the deprecated plugin (after trying it, and then trying to put tests into androidTest folder) because it solved quite some issues on Jenkins for me. The downside is that it does not recognizes the folder itself as java or android code, so code completion works with everything except the content of the folder (for example it sees correctly the base project and all dependencies).

    What I had to do run it in Android Studio was to create a JUnit (not Android) testrunner. It won't work out of the box probably, because the classpath order is messed up (although it works fine by just running tests in gradle).

    Basically the manual steps I had to do are:

    1. Run the junit testrunner in order to see the command line used by AS
    2. Edit the -classpath argument doing the following:

      • move junit > 3.8 at the top of the string (I guess because otherwise you will get the one within android, which is too old)
      • move robolectric as second if you reference it, otherwise real android methods will be found before robolectric ones
      • append your test classes output path to the end, so it will find your tests (remember to end your test classes with 'Test' otherwise they won't be found)
    3. Append the -classpath you just created to the runner VM options after -ea (I found this solution, or parts of it, in many places, a very good one is: http://kostyay.name/android-studio-robolectric-gradle-getting-work/ and it applies also to simple unit tests).

    An alternative I did not try but I considered has been suggested this morning (see last post): https://groups.google.com/forum/#!topic/adt-dev/Y8-ppkWell0

    I have a lot of scattered knowledge right now due to the many issues I discovered due to preview SW and the tons of info I had to go through to solve them, but if you have more specific issue on the topic, just let me know :)

    0 讨论(0)
  • 2020-12-31 12:47

    I think the answer should be now already in Android Studio 1.1 (and current gradle plugin). They introduced unit test support. It's still experimental, but less so than our previous efforts here :) See here.

    0 讨论(0)
提交回复
热议问题