Can't run android test suite: Exception in thr

2019-09-08 03:10发布

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条回答
趁早两清
2楼-- · 2019-09-08 03:50

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:

enter image description here

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.

查看更多
登录 后发表回答