The place where random ideas get written down and lost in time.

2021-08-11 - Android Testing : AndroidX “AndroidJUnit4” vs Robolectric

Category DEV

I feel like a case of deja vu so I need to write this down.

  • Robolectric: simulating an Android runtime working on top of the JVM, local dev machine. No emulator needed.
    • Used to be simple and straightforward. Since Robolectric 4 and recent android gradle updates, some things have been deprecated / changed making it harder to use.
  • AndroidX runner “AndroidJUnitRunner” tests which go in androidTest folder: run on device or emulator, and are essentially the modern version of the instrumentation tests.
  • AndroidX runner “AndroidJUnit4” tests which go in androidTest folder: run on device or emulator too ⇒ the test folder name indicates which build rule is used and where the test runs.
  • AndroidX runner “MockitoJUnitRunner” tests which go in the test folder: run on JVM.
    • This is provided by mockito-core and is basically a JUnit runner that also happens to auto-init all the @Mock instances. ⇒ Just a convenience over the usual Mock rule, no relation to Android framework.
    • How much of the Android framework can be used with that? ⇒ none
  • Robolectric with AndroidX tests:

What I have done for Cab v2:

  • Build.gradle > defaultConfig > testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  • ServersActivityTest:
    • @RunWith(AndroidJUnit4.class)
      @Config(application = TestMainApp.class)
      ApplicationProvider.getApplicationContext()
      ActivityScenario.launch(MainActivity.class)
  • The cabv2 TestMainApp derives from the LegacyMainApp and replaces the IAppComponent by the ITestAppComponent for testing. That’s how test modules are injected in the app.

Since updating B3, I was getting errors:

  • “robolectric RuntimeException Method not mocked”
  • They are “solved” by adding this to app gradle:
    • testOptions > unitTests >  returnDefaultValues = true
  • Which in turn creates another error: “java.lang.ClassNotFoundException: android.content.res.ApkAssets”
  • Real solution: following https://github.com/robolectric/robolectric/issues/4740
    • The dumb solution is to remove the m2 robolectric cache so that it gets downloaded again.


 Generated on 2025-01-18 by Rig4j 0.1-Exp-f2c0035