How can I test fragments with Robolectric?

Edit #4 & #5: In Robolectric 3.*, they split up the fragment starting functions. For support fragments, you will need to add a dependency to your build.gradle: testCompile “org.robolectric:shadows-supportv4:3.8” Import: org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment; For platform fragments, you don’t need this dependency. Import: import static org.robolectric.util.FragmentTestUtil.startFragment; They both use the same name of startFragment(). import static org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment; @RunWith(RobolectricTestRunner.class) … Read more

Robolectric vs Android Test Framework

Update Apr-2015: Gradle build tools and Android Studio now officially support unit testing and prevent android.jar from throwing stub (no real implementation) error. So, yes its possible to run tests on Java VM, when stubs are appropriately mocked. Its a start but is still not comparable with Robolectric’s power. There is also a third alternative, … Read more

Does Robolectric support API level?

Update: The annotation is now @Config(sdk = 18) (or @Config(sdk = Build.VERSION_CODES.JELLY_BEAN_MR2)) and the properties file mentioned in link is now robolectric.properties. Original Answer: You can use the @Config annotation to have Robolectric emulate an SDK version. You can put this : import org.robolectric.annotation.Config; @Config(emulateSdk = 18) // now @Config(sdk = 18) as of Robolectric … Read more

Testing custom Views with Robolectric

I test views in the same test class with the Activity that uses them. In this case I tell Robolectric to give an instance of that Activity and from that I get an instance of the inflated view: @Before public void setup(){ activity = Robolectric.buildActivity(MyActivity.class).create().get(); View view = LayoutInflater.from(activity).inflate(R.layout.myView, null); } @Test public void allElementsInViewProduct(){ … Read more

Confused about testCompile and androidTestCompile in Android Gradle

Simply testCompile is the configuration for unit tests (those located in src/test) and androidTestCompile is used for the test api (that located in src/androidTest). Since you are intending to write unit tests, you should use testCompile. Update: The main distinction between the two is the test sourceset runs in a regular Java JVM, whereas the … Read more

Testing ViewPager (and CursorLoader) with Robolectric

I’m not certain, but I would wager that the internal code is trying to use an AsyncTask to invoke the cursor loader’s loadInBackground() method. You might be seeing a deadlock because the AsyncTask tries to invoke onPostExecute(). That call will try to run in your main UI thread, which happens to be the thread of … Read more