我尝试测试我的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 /模拟器,但它不会影响任何东西。
我该怎么做才能解决问题? :(
答案 0 :(得分:0)
不要在构造函数中调用getActivity()方法。在setUp方法中使用它,重写。
@Override
public void setUp(){
super.setUp();
currentActivity=getActivity();
...
...
}
继续前进。
在类中声明currentActivity
作为EmptyActivity_