我关注了安卓的Hello, Testing教程一字不漏,但是当我运行它时,我收到了一个错误,其中包含以下失败跟踪:
java.lang.NullPointerException
at com.example.helloandroid.test.HelloAndroidTest.testText(HelloAndroidTest.java:72)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
异常出现在testText()的单条语句中:
public void testText() {
assertEquals(resourceString,(String)mView.getText());
}
我不明白为什么我会收到这个空指针异常,因为 resourceString
和 mView
都是在 onCreate()
中初始化的:
@Override
protected void setUp() throws Exception {
super.setUp();
mActivity = this.getActivity();
mView = (TextView) mActivity.findViewById(com.example.helloandroid.R.id.textview);
resourceString = mActivity.getString(com.example.helloandroid.R.string.hello);
}
在如此简单的应用程序中,有什么可以解释这一点?
最佳答案
回答我自己的问题:Hello, Testing教程是为 XML version 制作的“你好,Android”,不是第二个,dynamically constructed版本。
我通过修改 HelloAndroid 解决了这个问题的 onCreate()
:
if (false) { // don't use main.xml layout
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
else
setContentView(R.layout.main);
关于android - Android的 "Hello, Testing"教程中的JUnit NullPointerException错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979832/