简体   繁体   中英

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

I have 2 test classes that I need to run on a test suite one is RestaurantModelTest the 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!

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

ie it's not gonna work this way.

I hope, it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM