uTubeFan
uTubeFan

Reputation: 6794

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.java: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?

Upvotes: 1

Views: 2180

Answers (3)

sabadow
sabadow

Reputation: 5153

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

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

I hope it helps.

Upvotes: 1

uTubeFan
uTubeFan

Reputation: 6794

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);

Upvotes: 3

FoamyGuy
FoamyGuy

Reputation: 46856

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());
} 

Upvotes: 1

Related Questions