Mar 30, 2013

Android Robolectric: java.lang.RuntimeException: Stub! while using libraries like JSONObject


While running a unit test under Robolectric on Android, the following error occurs:
java.lang.RuntimeException: Stub!


  • When you step through the code, portions of it work just fine
  • The exception occurs after returning from a constructor
  • Some library code is being used, like JSONObject


As stated in the Robolectric help documentation:

Make sure that robolectric and its dependencies (including JUnit) appear before the Android API jars in the classpath.

In other words, assuming you set things up correctly, then from that point forward, all you have to do is be sure that your classes are coming from either Robolectric or pure Java. In my case, the code under test was using JSONObject and that was coming from the android jar. To fix this, I had to:

  1. Add the JSONObject jar to my test project's dependencies. Depending on how your project is setup, that could be as simple as copying it to the lib folder
  2. Re-order the dependencies in the classpath such that Roboelectric and the other Java jars appear before anything Android-related. In Eclipse, that looks like this:

In this case, I pulled Robolectric and JSON up to the top and pushed android and maps down to the bottom. After this change, my test worked perfectly.

1 comment: