2

我尝试测试我的 Activity,但遇到了问题:当我尝试运行 Android JUnit 项目时,它在启动时失败,并出现此堆栈跟踪:

junit.framework.AssertionFailedError: Exception in constructor: test (java.lang.NullPointerException
at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:100)
at com.sogemobile.saytv.api.UploadAvatarTest2.<init>(UploadAvatarTest2.java:16)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at junit.runner.BaseTestRunner.getTest(BaseTestRunner.java:118)
at android.test.AndroidTestRunner.getTest(AndroidTestRunner.java:148)
at android.test.AndroidTestRunner.setTestClassName(AndroidTestRunner.java:56)
at android.test.suitebuilder.TestSuiteBuilder.addTestClassByName(TestSuiteBuilder.java:80)
at android.test.InstrumentationTestRunner.parseTestClass(InstrumentationTestRunner.java:444)
at android.test.InstrumentationTestRunner.parseTestClasses(InstrumentationTestRunner.java:425)
at android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:370)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4382)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)

我的测试代码是:

 public class UploadAvatarTest2 extends ActivityInstrumentationTestCase2<EmptyActivity_> {

    public UploadAvatarTest2() {
         super(EmptyActivity_.class);
         getActivity();
    }

    public void test(){
    }

 }

我发现问题是“getActivity()”调用。如果我在“super(EmptyActivity_.class)”处放置断点,调试器甚至不会停止。但是如果我删除“getActivity()”字符串调试器将停止。它看起来很棒,但它是真的:) 我试图重新启动 eclipse/emulator 但它不会影响任何东西。

我应该怎么做才能解决问题?:(

4

1 回答 1

0

不要在构造函数中调用 getActivity() 方法。在 setUp 方法中使用它,被覆盖​​。

@Override

public void setUp(){
super.setUp();
currentActivity=getActivity();
...
...
}

进一步行动。

在类中声明currentActivity为私有对象EmptyActivity_

于 2014-09-08T13:30:39.240 回答