Can't run android test suite: Exception in thread “main” java.lang.ClassNotFoundException

若如初见. 提交于 2019-12-11 23:19:12

问题


I have 2 test classes that I need to run on a test suite one is RestaurantModelTestthe other is CartModelTest.class:

@Config(sdk = 16, manifest = "src/main/AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class RestaurantModelTest {

    //setUp code here...

    @Test
    public void testFindByLocation() throws Exception {
         //test code here
    }

}

So I followed some tutorials online and they specify to create a TestSuite class like this with my 2 classes to be tested:

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
        RestaurantModelTest.class,
        CartModelTest.class
})
public class ModelsTestSuite {

}

And then I must create a TestSuiteRunner class:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestSuiteRunner {


    public static void main(String[] args){
        Result result = JUnitCore.runClasses(ModelsTestSuite.class);
        for (Failure failure : result.getFailures()){
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());

    }
}

I'm using android studio and when I hate right-click > Run TestSuiteRunner...main() I get Exception in thread "main" java.lang.ClassNotFoundException:

any help really appreciated!


回答1:


All you need to do to run all the tests in suite - is to:

  1. Right-click in ModelsTestSuite
  2. Click "Run ModelsTestSuite"

That's it, all tests in the suite will be executed. You don't really need TestSuiteRunner class for that:

NB! While solving this problem, I found another bizarre one: unless I disabled instant run (Preferences -> Build, Execution, Deployment -> Instant Run -> Enable Instant Run - uncheck) in Android Studio 2.0, all my Robolectric tests were failing with java.lang.ClassNotFoundException. jFYI.

The reason you get java.lang.ClassNotFoundException is incompatibility of plain java projects and Android projects. You can read more here: Can Android Studio be used to run standard Java projects?

So, theoretically, to have TestSuiteRunner in this form, you could move it to separate Java library module and link Android app's module as a dependency for this Java lib. Unfortunately, you'd get this warning:

Warning:Ignoring dependency of module 'app' on module 'lib'. Java modules cannot depend on Android modules

i.e. it's not gonna work this way.

I hope, it helps.



来源:https://stackoverflow.com/questions/34317022/cant-run-android-test-suite-exception-in-thread-main-java-lang-classnotfound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!