开发者

JUnit NullPointerException error in Android's "Hello, Testing" tutorial

I followed Android's Hello, Testing tutorial verbatim, yet when I run it I receive an error with the following Failure Trace:

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.jav开发者_如何学编程a:1447)

The exception occurs in testText()'s single statement:

  public void testText() {
    assertEquals(resourceString,(String)mView.getText());
  }  

I don't understand why I am receiving this null pointer exception since both resourceString and mView are initialized in 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);
  }

What could explain this in such a simple app?


Answering my own question: The Hello, Testing tutorial is made for the XML version of "Hello, Android", not for the second, dynamically constructed version.

I fixed the problem by modifying HelloAndroid's 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);


I am not positive but I think the way you are trying to cast as a String might be part of the problem. Try mView.getText().toString() instead of casting it how you are now.

public void testText() {
    assertEquals(resourceString,(String)mView.getText());
} 


I fix it adding the @UiThreadTest to the test, like this:

@UiThreadTest
public void testText() {
  assertEquals(resourceString,(String)mView.getText());
}

I hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜