Working with the Android / Robolectric card - activated activity returns null on getResource

This is due to the use of the Robolectric platform for unit testing on Android. I get a null pointer exception for code that does not have problems during normal operation. I'm just starting out with roboelectric, so it's probably pretty simple.

Here is the challenge 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 a method called inside InitUtils that causes a crash

/ ** * Loads the XML into the member variable {@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 

Is there anything special for this to get the resource?

+6
android unit-testing robolectric
source share
1 answer

I don't know anything about this Robolectric, but getResources () returning null means that it is called before the environment 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 your tool thread is blocked until the main thread completes, using something like:

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

If you use startActivitySync, this will be done for you:

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

0
source share

All Articles