单元测试期间应用程序 class 出错

Getting error in Application class during unit testing

当我试图通过 robolectric 执行我的应用程序 class 时,我遇到了奇怪的异常。 我被困了几个小时。 有人可以帮我吗? 我的代码片段如下:

 java.lang.RuntimeException: Stub!

at android.test.ApplicationTestCase.__constructor__(ApplicationTestCase.java:5)
at android.test.ApplicationTestCase.<init>(ApplicationTestCase.java)
at com.grapplemobile.tmcplus.TmcPlusApplicationTest.<init>(TmcPlusApplicationTest.java:26)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.robolectric.RobolectricTestRunner$HelperTestRunner.createTest(RobolectricTestRunner.java:520)
at org.junit.runners.BlockJUnit4ClassRunner.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.robolectric.RobolectricTestRunner$HelperTestRunner.methodBlock(RobolectricTestRunner.java:530)
at org.robolectric.RobolectricTestRunner.evaluate(RobolectricTestRunner.java:247)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=11=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

我的代码如下:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class,sdk = 18)
public class MyApplicationTest extends ApplicationTestCase<MyApplication>{
  private MyApplication application;

   public  MyApplicationTest ()
  {
      super(MyApplication.class);
   }
   @Before
    public void setUp() throws Exception {
      // super.setUp();
      createApplication();
      application = getApplication();

   }

   @Test
   public void testonCreate() throws Exception {
   application.onCreate();
  }

不要将 JUnit 测试与仪器测试混合使用:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class,sdk = 18)
public class MyApplicationTest{
}

如果您需要应用程序实例,请使用 RuntimeEnvironment.application。如果你想测试应用程序本身,那么只需使用 new 创建它并调用它的方法,但它不应该是 Robolectric test