2011-03-31 17 views
1

我使用HelloAndroidTest教程從谷歌空指針:谷歌的Android HelloWorldTest失敗 - 收到的檢索資源

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測試。

這是非常基本的,但它確實需要一個活動被成功創建,並從HelloAndroid項目中獲取資源,這是我需要進行單元測試的功能。有想法該怎麼解決這個嗎?

+0

assertNotNull失敗或您收到NPE(如標題所述)? – 2011-04-01 02:35:55

+0

對,在這種情況下,assert not null在空指針上失敗,調整標題。 – 2011-04-01 14:55:44

+0

所以mAbility不爲空,只是爲了證明它添加assertnotNull(mActivity) – 2011-04-01 17:43:25

回答

0

我想我已經明白了。它看起來像活動需要在測試方法本身中創建。一旦我把它移到那裏,它就可以正常工作。 getActivity文檔實際上陳述了一些與此相關的內容,這正是最終引導我進入的東西。用不朽的MLK的話 - 終於自由了,終於自由了 - 終於自由了。

+0

雖然這樣可以解決它,但是當我redid HelloWorldTest時,它工作正常,並且不需要此修復程序。我沒有時間去追蹤我做錯了什麼。 – 2011-05-05 18:52:40

1

看着你的第一個代碼提交,我不認爲setUp接受任何參數,因此你的覆蓋方法和參數永遠不會被調用,因此你所有的實例變量都是null。