Loading...
Loading...
Use this skill to apply Android-team testing strategies — determinism, hermetic execution, Given-When-Then / Arrange-Act-Assert structure, naming conventions, and Hilt-based dependency replacement. Encodes which guidance actually lives on `/training/testing/fundamentals/strategies` (qualitative pyramid, network-access table) versus `/training/testing/instrumented-tests/stability` (determinism / flake) versus `/training/dependency-injection/hilt-testing` (`@HiltAndroidTest`, `HiltAndroidRule`, `@TestInstallIn`, `@UninstallModules`, `@BindValue`, rule ordering). Use when the user asks "how should I structure tests", "Given When Then or Arrange Act Assert", "how do I name test methods", "Hilt rule order", "@HiltAndroidTest", "@BindValue", "how to swap a binding for tests", "tests pass locally fail on CI", or "make tests deterministic".
npx skill4agent add skydoves/android-testing-skills applying-testing-strategies@HiltAndroidTestHiltAndroidRule@TestInstallIn@UninstallModules@BindValueRuleChain.outerRuleHiltAndroidRuleActivityScenarioRulecomposeTestRule../../concepts/understanding-the-testing-pyramid/SKILL.md../../concepts/choosing-what-to-test/SKILL.md../../doubles/picking-test-doubles/SKILL.md../organizing-test-source-sets/SKILL.md../../../compose/synchronization/synchronizing-with-idle/SKILL.md../../concepts/understanding-the-testing-pyramid/SKILL.mddagger.hilt.android.testing.HiltAndroidRuledagger.hilt.android.testing.HiltAndroidTestandroidTestImplementationkotlinx-coroutines-testRobolectricSystem.currentTimeMillis()Clock.systemDefaultZone()tasks/research/R8-android-fundamentals.md| Concept | Page that actually documents it |
|---|---|
| Qualitative pyramid ("many small, few big") | |
| Five-level Unit/Component/Feature/Application/RC table | |
| Network access per layer | |
| Determinism / flake handling | |
| Hermetic test definition | |
| Given-When-Then comment style | NEVER named on any page; only used in code samples |
| Arrange-Act-Assert | NEVER named on any page |
| Test naming | Only the backtick caveat on |
| |
/strategies/instrumented-tests/stability/training/testing/instrumented-tests/stabilitySystem.currentTimeMillis()Clock.systemDefaultZone()Instant.now()Clockkotlinx-coroutines-testDispatchers.IOrunBlockingdelayrunTestCoroutineDispatcherDispatchers.MainDispatchers.setMain(dispatcher)../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.mdMainTestClocktestOptions.animationsDisabled = trueSettings.Global.WINDOW_ANIMATION_SCALE = 0mainClock.autoAdvance = falsedocs/SPEC.mdRandom()UUID.randomUUID()pm clearClockClock.fixed(Instant.parse(...), ZoneId.of("UTC"))DispatchersDispatcherProviderDispatchers.setMain(StandardTestDispatcher())@BeforeRandomRandom(42)RandomProvidertestOptions.animationsDisabled = truebuild.gradle.ktspm clear <pkg>@Before/strategies/test-doubles"A hermetic test avoids all external dependencies, such as fetching data from the internet." —developer.android.com/training/testing/fundamentals/test-doubles
/strategies| Layer | Network access |
|---|---|
| Unit | None |
| Component | None |
| Feature | "supports mocked network access" |
| Application | n/a |
| Release Candidate | n/a |
/strategies/test-doubles/test-doubles/strategies/fundamentals/what-to-test/test-doubles/strategies/fundamentals// Given an instance of MyViewModel
val viewModel = MyViewModel(myFakeDataRepository)
// When data is loaded
viewModel.loadData()
// Then it should be exposing data
assertTrue(viewModel.data != null)developer.android.com/training/testing/fundamentals// When the Continue button is clicked
onView(withText("Continue")).perform(click())
// Then the Welcome screen is displayed
onView(withText("Welcome")).check(matches(isDisplayed()))developer.android.com/training/testing/fundamentalsGiven (Arrange) — set up the SUT and dependencies
When (Act) — invoke the behavior under test
Then (Assert) — assert on the resulting state or interaction/instrumented-tests"Note: Using backticks to name tests in Kotlin is only supported on devices running API 30 and above." —developer.android.com/training/testing/instrumented-tests
src/test/src/androidTest/minSdk >= 30camelCasesnake_case_with_underscoresmethodName_state_expectedloadUsers_emptyList_emitsEmptyState
applyCoupon_negativeTotal_emitsError
save_orchestratorMarksDirtyOncedeveloper.android.com/training/dependency-injection/hilt-testing"Hilt isn't necessary for unit tests, since when testing a class that uses constructor injection, you don't need to use Hilt to instantiate that class." —developer.android.com/training/dependency-injection/hilt-testing
"For integration tests, Hilt injects dependencies as it would in your production code. Testing with Hilt requires no maintenance because Hilt automatically generates a new set of components for each test." —developer.android.com/training/dependency-injection/hilt-testing
@HiltAndroidTestHiltAndroidRule@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
@Inject lateinit var userRepository: UserRepository
@Before fun inject() = hiltRule.inject()
}HiltAndroidRule/hilt-testingHiltAndroidRuleorder@Rule(order = 0)order = 101order = -1order = 0/hilt-testing"You must annotate any UI test that uses Hilt with. This annotation is responsible for generating the Hilt components for each test. Also, you need to add the@HiltAndroidTestto the test class." —HiltAndroidRuledeveloper.android.com/training/dependency-injection/hilt-testing
"To inject types into a test, usefor field injection. To tell Hilt to populate the@Injectfields, call@Inject." —hiltRule.inject()developer.android.com/training/dependency-injection/hilt-testing
@TestInstallIn@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [AnalyticsModule::class],
)
abstract class FakeAnalyticsModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}@HiltAndroidTest@UninstallModules@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@Module @InstallIn(SingletonComponent::class)
abstract class TestModule {
@Singleton @Binds
abstract fun bindAnalyticsService(impl: FakeAnalyticsService): AnalyticsService
}
}/hilt-testing"Warning: You cannot uninstall modules that are not annotated with. Attempting to do so causes a compilation error."@InstallIn
"Warning:can only uninstall@UninstallModulesmodules, not@InstallInmodules." —@TestInstallIndeveloper.android.com/training/dependency-injection/hilt-testing
@BindValue@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analyticsService: AnalyticsService = FakeAnalyticsService()
}@BindValue@CustomTestApplicationApplicationMultiDexApplication@CustomTestApplication(BaseApplication::class)
interface HiltTestApplicationHiltTestApplication_ApplicationtestInstrumentationRunnerArgumentsAndroidJUnitRunner@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) var settingsActivityTestRule = SettingsActivityTestRule(...)
}developer.android.com/training/dependency-injection/hilt-testingRuleChain@get:Rule
val chain: TestRule = RuleChain
.outerRule(HiltAndroidRule(this))
.around(InstantTaskExecutorRule())
.around(MainDispatcherRule())// WRONG — no structure; reader cannot find the act vs assert boundary
@Test
fun loadsUser() = runTest {
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
vm.load(UserId("u1"))
val state = vm.state.value
assertEquals("Alice", state.name)
assertFalse(state.isLoading)
}
// WRONG because: the test crams setup, action, and assertion together. With three or
// more lines per stage, readers cannot locate failures fast. Google's own samples use
// Given-When-Then comments as visual separators.// RIGHT
@Test
fun loadUser_seededId_emitsLoadedState() = runTest {
// Given a fake repo seeded with Alice
val repo = FakeUserRepository().apply { seed(User(UserId("u1"), "Alice")) }
val vm = UserViewModel(repo)
// When loading the seeded id
vm.load(UserId("u1"))
// Then the state is Loaded with Alice
assertEquals(UserUiState.Loaded(name = "Alice"), vm.state.value)
}// WRONG
@HiltAndroidTest
class HomeScreenTest {
@get:Rule val composeRule = createAndroidComposeRule<MainActivity>() // order = 0 by default
@get:Rule val hiltRule = HiltAndroidRule(this)
}
// WRONG because: with no order, JUnit picks ordering implementation-defined. The
// Activity may launch before Hilt's component is built, throwing at @Inject sites.
// Per /hilt-testing, HiltAndroidRule must run first.// RIGHT
@HiltAndroidTest
class HomeScreenTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1) val composeRule = createAndroidComposeRule<MainActivity>()
}// WRONG
class DueDateTest {
@Test fun reportsOverdue() {
val task = Task(dueAt = Instant.now().minusSeconds(60))
assertTrue(task.isOverdue()) // depends on real wall clock; flake risk on slow CI
}
}// RIGHT
class DueDateTest {
private val fixedNow = Instant.parse("2024-01-01T00:00:00Z")
private val clock = Clock.fixed(fixedNow, ZoneId.of("UTC"))
@Test fun reportsOverdue() {
val task = Task(dueAt = fixedNow.minusSeconds(60), clock = clock)
assertTrue(task.isOverdue())
}
}@BindValueevery { }// WRONG — mocking a Hilt-injected real instance
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
@Inject lateinit var analytics: AnalyticsService
@Test fun tracks() {
// analytics is the real production instance; tests now mutate prod state
every { (analytics as RealAnalyticsService).enabled = false } // does not compile
}
}// RIGHT — replace at the binding boundary
@UninstallModules(AnalyticsModule::class)
@HiltAndroidTest
class SettingsActivityTest {
@BindValue @JvmField
val analytics: AnalyticsService = FakeAnalyticsService()
@get:Rule(order = 0) val hiltRule = HiltAndroidRule(this)
}HiltAndroidRule@Rule(order = 0)@Rule(order = 1)/hilt-testingHiltAndroidRuleorder = 0hiltRule.inject()@Before@Inject@TestInstallIn@UninstallModules/training/testing/fundamentals/strategies/training/testing/instrumented-tests/stabilityClockDispatcherProviderRandomcamelCase_state_expected/instrumented-testsminSdk@BindValue@TestInstallIntestOptions.animationsDisabled = true@HiltAndroidTestHiltAndroidRuleorder@Rule(order = 0)@HiltAndroidTest@InjecthiltRule.inject()@BeforeFake*src/androidTest/src/test/core-testingInstant.now()System.currentTimeMillis()Random()testOptions.animationsDisabled = truebuild.gradle.ktsdeveloper.android.com/training/testing/fundamentals/strategiesdeveloper.android.com/training/testing/fundamentals/test-doublesdeveloper.android.com/training/testing/instrumented-tests/stabilitydeveloper.android.com/training/testing/instrumented-testsdeveloper.android.com/training/dependency-injection/hilt-testing@HiltAndroidTestHiltAndroidRule@TestInstallIn@UninstallModules@BindValue@CustomTestApplicationtasks/research/R8-android-fundamentals.mdMainDispatcherRuletestutils/testutils-ktx/src/jvmMain/kotlin/androidx/testutils/MainDispatcherRule.jvm.kt../../concepts/understanding-the-testing-pyramid/SKILL.md../../concepts/choosing-what-to-test/SKILL.md../../doubles/picking-test-doubles/SKILL.md../organizing-test-source-sets/SKILL.md../../../jvm-tests/coroutines/testing-coroutines-with-runtest/SKILL.md../../../jvm-tests/coroutines/testing-flows-with-turbine/SKILL.md../../../jvm-tests/runner/configuring-junit4-on-android/SKILL.md../../../jvm-tests/robolectric/using-robolectric-correctly/SKILL.md../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md../../../instrumentation/scenarios/launching-activities-with-activityscenario/SKILL.md../../../adb/observability/extracting-logs-with-logcat/SKILL.md