Robolectric: Shadows, Setup & Activities
Robolectric is a unit testing framework for Android that lets Android-dependent code (Activities, Views, SDK classes) run and be tested directly on a regular JVM, without an actual device or emulator -- providing a simulated Android environment for fast, standard unit tests.
Basic Test Setup
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33]) // simulate a specific Android API level --
// list multiple to catch version-specific bugs
class MainActivityTest {
@Test
fun `clicking button updates text`() {
val activity = Robolectric.buildActivity(MainActivity::class.java)
.create().resume().get() // explicit control over lifecycle stages
val button = activity.findViewById<Button>(R.id.submitButton)
button.performClick()
val label = activity.findViewById<TextView>(R.id.resultLabel)
assertThat(label.text.toString()).isEqualTo("Submitted!")
}
}Shadow Classes: How the Simulation Works
When test code calls a method on a real Android TextView, Robolectric intercepts the call and routes it to a ShadowTextView implementation that can actually run on the JVM -- the real Android framework classes have no meaningful implementation outside an actual Android runtime.
Real Behavior, Not Just Mocked Calls
// Robolectric's shadow SharedPreferences is a genuinely functioning
// in-memory store -- write, then read back to verify REAL round-trip
// persistence, not just "was putString() called with these args"
val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
prefs.edit().putString("username", "alice").apply()
assertThat(prefs.getString("username", null)).isEqualTo("alice")Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free