android - Android的 "Hello, Testing"教程中的JUnit NullPointerException错误

标签 android junit

我关注了安卓的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());
  }  

我不明白为什么我会收到这个空指针异常,因为 resourceStringmView 都是在 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/

相关文章:

java - 如何在 Eclipse 中使用 JUnit4 测试 jar 文件?

java - 有没有办法覆盖 JUnit 以将响应发送回另一个方法?

java - 可以从传递 String 参数的资源中加载 R.drawable 吗?

java - 相当于 JUnit5 的 @RunWith(JUnitPlatform.class)

android - cverror android 断言失败 (scn == 3) Android

android - 在实时应用程序的后台运行重复任务

使用 Junit 的 Spring 测试 session 范围 bean

java - HttpClientBuilder() 在 Java IDE 中抛出错误,因为“HttpsClientBuilder() 在 org.apache.http.impl.client.HttpClient.Builder 中的访问受到保护”

android - ImageView 将大图像缩小为模糊的小图像

android - 启动新 Activity 的 Intent 非常慢 :(