android - Google 的 Android HelloWorldTest 失败 - 在检索资源时收到空指针

标签 android unit-testing junit

我正在使用 Google 的 HelloAndroidTest 教程:

http://developer.android.com/resources/tutorials/testing/helloandroid_test.html .

这是测试类:

package com.example.helloandroid.test;

import com.example.helloandroid.HelloAndroid;

import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;

public class HelloAndroidTest extends
        ActivityInstrumentationTestCase2<HelloAndroid> {

    private HelloAndroid mActivity;
    private String resourceString;
    private TextView mView;

    public HelloAndroidTest() {
        super("com.example.helloandroid", HelloAndroid.class);
    }


    protected void setUp(TextView mView) 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);
    }

    public void testPreconditions() {
        assertNotNull(mView);       // <== always null
        //System.out.println("Resourse string: " + resourceString);
        //assertNotNull(resourceString); // <== always null (when run)
    }

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

这是 HelloAndroid 类:

package com.example.helloandroid;


import android.app.Activity;

import android.os.Bundle;

    public class HelloAndroid extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }

这是 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/textview" xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="@string/hello"/>

和strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello Android!</string>
    <string name="app_name">Hello, Android</string>
</resources>

mView 和资源字符串都未通过各自的 notNull 测试。

这是非常基本的,但它确实需要成功创建 Activity 并从 HelloAndroid 项目中提取资源,这是我进行单元测试所需的功能。有想法该怎么解决这个吗?

最佳答案

查看您提交的第一个代码,我认为 setUp 不接受任何参数,因此永远不会调用带有参数的重写方法,因此您的所有实例变量均为 null。

关于android - Google 的 Android HelloWorldTest 失败 - 在检索资源时收到空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5506674/

相关文章:

Android 订阅取消 -> 如何通知和测试?

java - 使用带有 OnException 定义的 adviceWith 进行 Camel 路由测试

javascript - Mocha before 在 It block 之后执行

java - 如何创建一个为测试脚本传递参数的 webdriver 函数?

android - 如何更改/重置处理程序后延迟时间?

Android Lollipop - PackageInstaller.Session commit()

java - 如何在单元测试中站起来然后关闭 Solr 实例?

java - JUNIT初始化错误

java - 我的 Eclipse 无法再运行(或调试)我的 JUnit 测试

android - 从指定位置偏移绘制线性渐变