How to run a test method or class as an Android Test in Android Studio

Issue

I am using Android Studio 0.2.4, but I assume this question can pertain to IntelliJ in general. My tests are under src/instrumentTest/java and all extend AndroidTestCase. When I run all the tests (say by right clicking on the source folder and clicking “Run…”) the tests run just fine on the Android emulator as Android Tests (as seen under the Run/Debug Configurations).

But if I try to run a single test method or test class the same way (right click on the method and click “Run…”), the test runs as a normal JUnit test not on the emulator, which of course fails (stack trace below). Even if I try to create a new Run Configuration, I see no way a creating anything other than a JUnit configuration.

From the IDE, how do run a test method or test class as an Android Test?

Exception in thread "main" java.lang.NoClassDefFoundError: junit/textui/ResultPrinter
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:188)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:113)
Caused by: java.lang.ClassNotFoundException: junit.textui.ResultPrinter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 3 more

Solution

For anyone still following, this works in Android Studio 0.2.8. There are three states you need to be aware of though.

  1. If you’ve never run the test method or class before, there will be no saved run configuration. So right click on the method or class and there should be a right arrow next to Run which displays the name of your test. Choose the one that has the Android symbol.

  2. If you’ve run the test method or class as a regular JUnit test before, then Android Studio will have saved that configuration and there will be no right arrow or options under Run in the context menu. In that case, in the file menu go to Run->Edit Configurations…, find your test under the JUnit section, and delete it. Then you should be in state (1).

  3. If you’ve run the test method or class as an Android test before, then Android Studio will have saved that configuration and there will be no right arrow or options under Run in the context menu. Just selecting Run should work.

Answered By – Nathan Taylor

Leave a Comment