Loading...
Loading...
Use this skill to pick the right test double — fake, mock, stub, spy, dummy, or Robolectric shadow — for an Android test. Encodes Google's verbatim preference order ("fakes ... are preferred", "Fakes are preferred over stubs for simplicity", "Fakes or mocks are therefore preferred over spies"), gives Android examples (in-memory `FakeUserRepository`, `mockk<UserRepository>()`, `ShadowSystemClock`), and a decision matrix mapping intent to the correct double. Use when the user asks "fake or mock", "should I use Mockito here", "how do I replace this dependency in tests", "what's the difference between a stub and a mock", "spy vs mock", or mentions `mockk`, `every { } returns`, `verify { }`, `org.mockito`, `argumentCaptor`, `Robolectric` shadows, `ShadowSystemClock`, or `FakeRepository`.
npx skill4agent add skydoves/android-testing-skills picking-test-doubles/training/testing/fundamentals/test-doubles../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md../../../jvm-tests/mocking/mocking-with-mockk/SKILL.mdverify(repo).getUser(any())RobolectricwhenevereveryverifyargumentCaptor../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md../../strategies/applying-testing-strategies/SKILL.md../../concepts/choosing-what-to-test/SKILL.md../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.mdmockito-coremockito-kotlinio.mockk:mockktestImplementation../../strategies/organizing-test-source-sets/SKILL.mdorg.robolectric:robolectrictestImplementationtestOptions.unitTests.includeAndroidResources = truedeveloper.android.com/training/testing/fundamentals/test-doubles"Fake: A test double that has a 'working' implementation of the class, but it is implemented in a way that makes it good for tests but unsuitable for production. Example: an in-memory database. Fakes don't require a mocking framework and are lightweight. They are preferred." —developer.android.com/training/testing/fundamentals/test-doubles
"Mock: A test double that behaves how you program it to behave and that has expectations about its interactions. Mocks will fail tests if their interactions don't match the requirements that you define. Mocks are usually created with a mocking framework to achieve all this. Example: Verify that a method in a database was called exactly once." —developer.android.com/training/testing/fundamentals/test-doubles
"Stub: A test double that behaves how you program it to behave but doesn't have expectations about its interactions. Usually created with a mocking framework. Fakes are preferred over stubs for simplicity." —developer.android.com/training/testing/fundamentals/test-doubles
"Spy: A wrapper over a real object which also keeps track of some additional information, similar to mocks. They are usually avoided for adding complexity. Fakes or mocks are therefore preferred over spies." —developer.android.com/training/testing/fundamentals/test-doubles
"Dummy: A test double that is passed around but not used, such as if you just need to provide it as a parameter. Example: an empty function passed as a click callback." —developer.android.com/training/testing/fundamentals/test-doubles
"Shadow: Fake used in Robolectric." —developer.android.com/training/testing/fundamentals/test-doubles
ShadowSystemClockShadowLooperShadowApplication../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md"Fakes don't require a mocking framework and are lightweight. They are preferred."
"Fakes are preferred over stubs for simplicity."
"Fakes or mocks are therefore preferred over spies."
Fake > Mock ≈ Stub > Spy
↑ (mock when verifying interactions; stub when only canned data)FakeUserRepository/test-doublesval const UserAlice = User("Alice")const valval consttasks/research/R8-android-fundamentals.md// RIGHT — fake repository with an in-memory map
class FakeUserRepository : UserRepository {
private val users = mutableMapOf<UserId, User>()
override suspend fun get(id: UserId): User? = users[id]
override suspend fun save(user: User) {
users[user.id] = user
}
override fun observeAll(): Flow<List<User>> = flow {
while (currentCoroutineContext().isActive) {
emit(users.values.toList())
delay(100)
}
}
// Test-only seeding helpers; production interface does NOT expose these.
fun seed(vararg users: User) {
users.forEach { this.users[it.id] = it }
}
fun clear() = users.clear()
}
@Test
fun loadsSeededUser() = runTest {
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
assertEquals("Alice", vm.state.value.name)
}every { }mockk<UserRepository>()markDirty(id)@Test
fun save_marksDirty_exactlyOnce() = runTest {
val repo = mockk<UserRepository>(relaxUnitFun = true)
val syncQueue = mockk<SyncQueue>(relaxUnitFun = true)
val sut = UserSaveOrchestrator(repo, syncQueue)
sut.save(User(UserId("u1"), "Alice"))
coVerify(exactly = 1) { syncQueue.markDirty(UserId("u1")) }
}@Test
fun save_marksDirty_exactlyOnce() = runTest {
val repo: UserRepository = mock()
val syncQueue: SyncQueue = mock()
val sut = UserSaveOrchestrator(repo, syncQueue)
sut.save(User(UserId("u1"), "Alice"))
verify(syncQueue).markDirty(UserId("u1"))
verifyNoMoreInteractions(syncQueue)
}@Test
fun loadsCachedAvatarUrl() = runTest {
val avatarApi: AvatarApi = mock()
whenever(avatarApi.getUrl(UserId("u1"))).thenReturn("https://cdn/u1.png")
val sut = AvatarPresenter(avatarApi)
sut.load(UserId("u1"))
assertEquals("https://cdn/u1.png", sut.url.value)
// Note: no verify {} — this is a stub, not a mock.
}AvatarApiFakeAvatarApi// WORKS but DISCOURAGED
val realCache = LruCache<String, Bitmap>(8)
val spied = spyk(realCache)
every { spied.evictAll() } answers { /* no-op for the test */ }LruCacheevictAllval noOpClickHandler: () -> Unit = {} // dummy — type-checks, never invoked
val sut = ClickableComponent(onClick = noOpClickHandler)
sut.bind(...) // test does not interact with onClick at allShadowSystemClockSystemClock.uptimeMillis()@RunWith(AndroidJUnit4::class)
class TimerTest {
@Test
fun reportsElapsedTime() {
ShadowSystemClock.setCurrentTimeMillis(0)
val timer = Timer()
ShadowSystemClock.advanceBy(Duration.ofMillis(1500))
assertEquals(1500L, timer.elapsed())
}
}ShadowSystemClockfinalThe intent of the test Pick
----------------------------------------------------------------
Need a working substitute for a class with state Fake
(in-memory DB, in-memory user map, in-memory clock)
Need to verify a specific interaction happened Mock
("markDirty was called once with id u1")
Need a canned return value, no behavior, no verification Stub
(and a Fake would be heavyweight for this one method)
Need partial real / partial fake on the same class Spy (last resort; refactor preferred)
Need a placeholder so a parameter type-checks Dummy
Need to substitute an Android framework class (final API) Shadow (Robolectric)// WRONG — using a mock to provide state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
val repo = mockk<UserRepository>()
coEvery { repo.get(UserId("u1")) } returns User(UserId("u1"), "Alice")
coEvery { repo.get(UserId("u2")) } returns User(UserId("u2"), "Bob")
coEvery { repo.observeAll() } returns flowOf(
listOf(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
)
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
assertEquals("Alice", vm.state.value.name)
}
// WRONG because: the test uses a mocking framework purely to seed data. Per /test-doubles:
// "Fakes are preferred over stubs for simplicity" and stubs are at least the lighter form
// of mock-as-data-source. A FakeUserRepository compiles, has no every {} ceremony, and
// the seed helper is reusable across tests.// RIGHT — fake provides state; ViewModel test asserts state
@Test
fun loadsAndDisplaysFirstUser() = runTest {
val repo = FakeUserRepository().apply {
seed(User(UserId("u1"), "Alice"), User(UserId("u2"), "Bob"))
}
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
assertEquals("Alice", vm.state.value.name)
}// WRONG — verifying a method call on a fake
@Test
fun save_callsRepository() = runTest {
val repo = FakeUserRepository()
val sut = UserSaveOrchestrator(repo)
sut.save(User(UserId("u1"), "Alice"))
// Now the test wants to verify save() was called. Fakes don't track calls.
// Tempting fix: switch to spyk(repo). DON'T.
val tracking = spyk(repo)
coVerify { tracking.save(any()) }
}
// WRONG because: this confuses "did the right state result?" (fake territory) with
// "was the right method called?" (mock territory). Pick one. If the test is verifying
// state, assert on repo.get(UserId("u1")) instead. If the test is verifying interaction,
// drop the fake and use a mock.// RIGHT — fake answers state assertions
@Test
fun save_persistsUser() = runTest {
val repo = FakeUserRepository()
val sut = UserSaveOrchestrator(repo)
sut.save(User(UserId("u1"), "Alice"))
assertEquals(User(UserId("u1"), "Alice"), repo.get(UserId("u1")))
}
// RIGHT — mock answers interaction assertions (separate test)
@Test
fun save_emitsSyncSignal() = runTest {
val repo: UserRepository = mock()
val syncQueue: SyncQueue = mock()
val sut = UserSaveOrchestrator(repo, syncQueue)
sut.save(User(UserId("u1"), "Alice"))
verify(syncQueue).markDirty(UserId("u1"))
}// WRONG
val cache = spyk(LruCache<String, Bitmap>(8))
every { cache.put(any(), any()) } answers {
// intercept and log
println("put: ${invocation.args[0]}")
callOriginal()
}/test-doubles// RIGHT
class RecordingCache : Cache<String, Bitmap> {
val puts = mutableListOf<Pair<String, Bitmap>>()
override fun put(key: String, value: Bitmap) { puts += key to value }
override fun get(key: String): Bitmap? = null
}// WRONG — production module with no test override
@Module @InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds abstract fun bind(impl: RealUserRepository): UserRepository
}
@HiltAndroidTest
class HomeScreenTest {
@Inject lateinit var repo: UserRepository // real repo, real DB, slow + non-hermetic
// ...
}// RIGHT — replace at the module boundary
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [RepositoryModule::class],
)
abstract class FakeRepositoryModule {
@Binds abstract fun bind(fake: FakeUserRepository): UserRepository
}../../strategies/applying-testing-strategies/SKILL.md/test-doubles../../concepts/choosing-what-to-test/SKILL.mdFakeUserRepository/test-doublesval const UserAlice = User(...)private valconst valFakeXRepositorytestFixturescore-testingmock<T>()wheneverargumentCaptorandroidx/mockk<X>()mock<X>()verify { }verify(x)FakeXspyk(x)spy(x)FakeXRepositoryFake*@TestInstallIn@UninstallModules@BindValueevery { }val const UserAlice/test-doublesdeveloper.android.com/training/testing/fundamentals/test-doublesdeveloper.android.com/training/testing/local-testsdeveloper.android.com/training/dependency-injection/hilt-testing@TestInstallIn@UninstallModules@BindValueHiltAndroidRuletasks/research/R8-android-fundamentals.mdval const UserAlicedeveloper.android.com/develop/ui/compose/testing../../concepts/understanding-the-testing-pyramid/SKILL.md../../concepts/choosing-what-to-test/SKILL.md../../strategies/applying-testing-strategies/SKILL.md../../strategies/organizing-test-source-sets/SKILL.md../../../jvm-tests/mocking/mocking-with-mockito/SKILL.md../../../jvm-tests/mocking/mocking-with-mockk/SKILL.md../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md