Testing
Android Development with Compose: Production & Publishing
Course 6 ยท Chapter 2 ยท Proving It Works
Android Development with Compose: Architecture & Data kept pointing here: "testing gets its own treatment". The architecture you built was designed for it. Because the screen is stateless, the ViewModel takes its repository in its constructor and the data layer has fakes, most of your app can be tested without running the whole thing.
ui-test-junit4 dependency and a debug manifest dependency for createComposeRule(); createComposeRule() when no specific activity is needed, createAndroidComposeRule when you need the activity; the sample pattern onNodeWithText(...).performClick() then .assertIsDisplayed(); the tests wait for the UI to be idle before acting; they are instrumented tests under src/androidTest; the Compose rules use a StandardTestDispatcher by default; and combining createComposeRule with runTest gives two separate clocks, so advancing time in one does not advance the other, with runComposeUiTest (in the v2 testing APIs) as the fix.
Room migration tests: exported schema files should be kept in version control; the schema location is set through Room's Gradle plugin; MigrationTestHelper creates a database at an old version, you insert data with raw SQL, then runMigrationsAndValidate migrates and validates the schema, but you must check the data yourself; auto-migrations need exportSchema = true; and there is an older room-testing artifact and a newer room3-testing one, so check which your project uses.
From earlier chapters: Dispatchers.setMain with a test dispatcher, and fakes or mocks for a ViewModel's repository.
Not found in the searches (general knowledge): the split between local and instrumented tests, backgroundScope, performTextInput, testTag, the Gradle plugin's exact id, and the migration code. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
What Kind of Test Where
| Test | Where it runs | Folder | Speed |
|---|---|---|---|
| JSON parsing, mappers, plain logic | Your computer (local) | src/test | Seconds |
| ViewModel with fakes | Local | src/test | Seconds |
| Room DAO (in-memory database) | Device or emulator (instrumented) | src/androidTest | Slower |
| Room migration | Instrumented | src/androidTest | Slower |
| Compose UI (docs: instrumented) | Instrumented | src/androidTest | Slower |
(general knowledge) Local tests need no Android at all, so you can run them dozens of times a minute; instrumented tests need an emulator or phone. Put as much as you can in the first group, which is exactly what the earlier chapters' structure allows.
Local Tests: the ViewModel
(docs, from the coroutines chapter's sources) A ViewModel's viewModelScope uses Dispatchers.Main, which does not exist in a plain local test. The fix the docs give is to replace Main with Dispatchers.setMain and a test dispatcher. Wrapping that in a JUnit rule means each test class needs only one line:
- Fakes over mocks, here. (docs) The guides say tests can pass fakes or mocks. A fake is a small working stand-in (Chapter 5's
FakeNotesRepository); (general knowledge) it keeps tests readable and survives refactoring better than a mocking library's setup. - Why the collector. The ViewModel's state uses
WhileSubscribed(Chapter 3), so without a collector the upstream does not run anduiState.valuewould not change.backgroundScope(general knowledge) is a scope fromrunTestthat is cancelled when the test ends. runTestruns coroutine code with a virtual clock, sodelaycosts no real time (general knowledge).
Instrumented Tests: the DAO
(general knowledge) An in-memory database vanishes when closed, so every test starts clean. This is the Chapter 4 test again, now with the runner annotation it needs. (docs) It lives in src/androidTest and needs a device or emulator.
Compose UI Tests
Chapter 1 of Android Development with Compose: Architecture & Data made NotesScreen stateless: it takes a state and callbacks. That is what makes it testable: no ViewModel, no database; you hand it a state and look at the result.
- (docs)
createComposeRule()is the one to use when you do not need a specific activity;createAndroidComposeRulegives access to the activity. - (docs) Tests wait for the UI to be idle before acting or asserting, so you do not write sleeps.
- (general knowledge) You find nodes by text, by tag (
Modifier.testTag) or by other properties of the semantics tree, the same information that accessibility services use. That is a good reason to give icons acontentDescription: it helps users and tests. - (docs) The two-clocks warning. Do not mix
createComposeRulewithrunTestin one test: they have separate clocks. If you need coroutine control inside a UI test, the docs point torunComposeUiTestand the v2 testing APIs; read that page before you start.
(docs, from the Hilt chapter's sources) Tests that use Hilt itself need hilt-android-testing, test compilers on kspAndroidTest and a test activity marked @AndroidEntryPoint. Because this app uses constructor injection, none of the tests above needs it.
A Real Migration, and Its Test
Android Development with Compose: Architecture & Data 7 told you to uninstall the app after changing the entity. Real users cannot do that. Suppose you want to let notes be pinned: add a column, raise the version to 3, and write a migration.
- (docs) Room exports the schema as JSON at compile time; keep those files in version control so older versions can be recreated for testing. The location is set through Room's Gradle plugin (check its current id and syntax in the docs).
- (general knowledge)
@ColumnInfo(defaultValue = "0")should match the SQL default, so Room's schema validation agrees with what the migration produced. - The code shows the Room 2.x form. (docs, from Chapter 4) In Room 3.0, migrations use
SQLiteConnectioninstead ofSupportSQLiteDatabaseand the package isandroidx.room3.
(docs) The helper creates the old database, you insert a row with raw SQL, runMigrationsAndValidate migrates and validates the schema, and then you check the data: the helper does not check that your rows survived. The test above does exactly that.
What Makes a Test Worth Having
- Test behaviour, not wiring. "Adding an empty note shows a message" outlives refactoring; "the ViewModel calls
updatetwice" does not (general knowledge). - Test the edges. Empty input, a failed network call, an old database version.
- No sleeping. Use the test dispatcher's virtual time and the Compose rule's idle waiting instead of real delays (general knowledge, and the docs on idle waiting).
- A test you never saw fail is unproven. Break the code on purpose once and watch the test catch it (general knowledge).
Try It Yourself
Add the dependencies, the MainDispatcherRule and the two ViewModel tests, and run them. Then add a third test that checks the sort order setting changes the order of the notes. Report whether they pass and how long they took.
Write the two Compose UI tests and a third that checks the Refresh button is disabled while isRefreshing is true. Run them on an emulator and report what you needed to add (the tag, the manifest dependency, anything else).
Add the pinned column, raise the database to version 3, write the migration and the migration test, and set up schema export. Then break the migration on purpose (a wrong default, say) and confirm the test fails. Report how you configured the schema location.
createComposeRule against createAndroidComposeRule; the find, click, assert pattern; idle waiting; Compose tests being instrumented; the StandardTestDispatcher default; the two-clocks warning and runComposeUiTest; exported schemas in version control and the Gradle plugin's schema location; the MigrationTestHelper flow and the need to check data yourself; auto-migrations needing exportSchema = true; the room-testing and room3-testing artifacts; the Hilt testing setup and Dispatchers.setMain (earlier chapters).General knowledge, not checked: the local against instrumented split;
backgroundScope; performTextInput and testTag; the semantics tree remark; the Room Gradle plugin's id; the migration and its SQL; the column default and schema validation remark; the advice on what makes a test worth having; every import and the code as written.Not verified: the
room-testing constructor and artifact for your Room line; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.Sources: Test your Compose layout (developer.android.com), Configure the test environment with v2 testing APIs (developer.android.com), Common patterns (developer.android.com), Migrate your Room database (developer.android.com), MigrationTestHelper API reference (developer.android.com), Hilt testing guide (developer.android.com).