Google's Android HelloWorldTest fail - receives null pointer on retrieving resource
I'm using the HelloAndroidTest tutorial from Google:
http://developer.android.com/resources/tutorials/testing/helloandroid_test.html.
Here's the test class:
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.getAc开发者_StackOverflowtivity();
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());
}
}
Here's the HelloAndroid class:
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);
}
}
This is 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"/>
And strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello Android!</string>
<string name="app_name">Hello, Android</string>
</resources>
Both mView and resource string fail their respective notNull tests.
This is pretty basic, but it does require an activity to be successfully created and the resource pulled from the HelloAndroid project, which is the functionality I need to get on with unit testing. Any ideas on how to fix this?
Looking at your first code submission, I don't think setUp takes any parameters, therefore your overridden method with a parameter would never get called and therefore all your instance vars are null.
I think I've got it. It looks like the activity needs to be created in the test method itself. Once I moved it there, it works fine. The getActivity documentation actually states something to that effect, which is what finally clued me in. In the words of the immortal MLK - Free at last, free at last - free at last.
精彩评论