开发者

Android / Robolectric frame work - Instantiated activity returns null on getResource

This has to do with using the Robolectric framework for unit testing on android. I'm getting a null pointer exception on code which has no problem when running normally. I'm just starting on the roboelectric, so it's probably pretty simple.

Here is the calling code for Testing :

@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");

}

Here is the method called within in InitUtils which crashes

/** 开发者_Go百科 * Loads the XML into the {@see mQuestions} class member variable * */

   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

Is there something special I need to do for this to retrieve the resource?


I don't know anything about this Robolectric thing, but getResources() returning null means it is being called before the framework has called Activity.onCreate(). I don't know where you got this Activity from, but if you are doing unit testing on top of Instrumentation you need to make sure that your instrumentation thread blocks until the main thread has finished executing, using something like:

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

If you are using startActivitySync this will be done for you:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜