2011-03-31 17 views
6

這與在Android上使用Robolectric框架進行單元測試有關。我在運行正常時沒有問題的代碼上得到空指針異常。我剛剛開始使用摩托車,因此它可能非常簡單。Android/Robolectric框架工作 - 實例化活動在getResource上返回null

下面是測試調用代碼:

@Test 
    public void testInitUtilsInitSequenceNumberIsRandom() { 

    // create an activity for reference 
    InitUtils initUtils = new InitUtils(); 

    // do static initialization to parse questions into memory 
    InitUtils.initialize(initUtils); // <============ the call from roboelectric framework 

    // retreive app state 
    AppState appState = (AppState) initUtils.getApplicationContext(); 

    // fill in later 
    fail("not implemented"); 

} 

以下是在InitUtils內調用的方法,其崩潰

/** * 加載XML到{@see mQuestions}類成員可變 * */

public static void initializeQuestions(Activity activity, AppState appState)     { 

    /* create XML Parser */ 
    XmlResourceParser questionBatch;  
    /* local question variable */ 
    Question question = null; 

    /* retrieve the XML for parsing */ 
    // =============== This returns null ============================== 
    questionBatch = activity.getResources().getXml(R.xml.questions); 

    /* Parse the XML */ 
    int eventType = -1;  
    /* iterate through XML */ 
    while (eventType != XmlResourceParser.END_DOCUMENT) { 
     if (eventType == XmlResourceParser.START_TAG) { 

     /* Get the questions */ 
     // ================================= NPE exception ====================== 
     String strName = questionBatch.getName(); 
     ...etc 

是不是有什麼特別的,我需要爲此做檢索資源?

+0

是它崩潰哪行? – jlindenbaum 2011-06-20 20:14:09

+0

@Jack BenNimble你LogCat說在這裏顯示? – Herry 2011-10-08 13:15:24

回答

0

我對這個Robolectric的東西一無所知,但getResources()返回null意味着它在框架調用Activity.onCreate()之前被調用。我不知道你從哪裏得到這個Activity,但是如果你在Instrumentation上進行單元測試,你需要確保你的檢測線程阻塞,直到主線程執行完畢,使用類似的方法:

http://developer.android.com/reference/android/app/Instrumentation.html#waitForIdleSync()

如果您正在使用startActivitySync這會爲你做:

http://developer.android.com/reference/android/app/Instrumentation.html#startActivitySync(android.content.Intent)

+0

Robolectric是不同的,應該創建一個影子資源對象,所以這個Android測試樣式不是答案。 – Blundell 2011-10-21 23:03:27