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.

What was checked, and how: read this first
Checked in the docs (two searches, summaries only): Compose UI tests: the setup needs the 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

TestWhere it runsFolderSpeed
JSON parsing, mappers, plain logicYour computer (local)src/testSeconds
ViewModel with fakesLocalsrc/testSeconds
Room DAO (in-memory database)Device or emulator (instrumented)src/androidTestSlower
Room migrationInstrumentedsrc/androidTestSlower
Compose UI (docs: instrumented)Instrumentedsrc/androidTestSlower

(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.

// Module build.gradle.kts (versions are placeholders; the Compose test libraries follow your Compose BOM) dependencies { // Local tests (src/test): run on your computer testImplementation("junit:junit:<junit-version>") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:<coroutines-version>") // Instrumented tests (src/androidTest): run on a device or emulator androidTestImplementation("androidx.compose.ui:ui-test-junit4") androidTestImplementation("androidx.test.ext:junit:<androidx-test-version>") androidTestImplementation("androidx.room:room-testing:<room-version>") // Room 3.0: room3-testing // Needed by createComposeRule(): the test manifest, in debug builds only debugImplementation("androidx.compose.ui:ui-test-manifest") }

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:

import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description // Replaces Dispatchers.Main for every test that uses it (docs: Dispatchers.setMain) @OptIn(ExperimentalCoroutinesApi::class) class MainDispatcherRule( private val dispatcher: TestDispatcher = UnconfinedTestDispatcher() ) : TestWatcher() { override fun starting(description: Description) = Dispatchers.setMain(dispatcher) override fun finished(description: Description) = Dispatchers.resetMain() }
// FakeNotesRepository: let a test choose what refresh() returns class FakeNotesRepository : NotesRepository { var refreshResult: RefreshResult = RefreshResult.Success // ...the notes flow, addNote and deleteNote from Chapter 5... override suspend fun refresh(): RefreshResult = refreshResult }
// app/src/test/.../NotesViewModelTest.kt (a local test: fast, no emulator) class NotesViewModelTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private fun viewModel(repository: FakeNotesRepository = FakeNotesRepository()) = NotesViewModel(repository, FakeSettingsRepository()) @Test fun emptyNoteShowsMessage() = runTest { val vm = viewModel() backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect { } } vm.addNote(" ") assertEquals("A note cannot be empty", vm.uiState.value.userMessage) } @Test fun failedRefreshShowsMessage() = runTest { val repository = FakeNotesRepository().apply { refreshResult = RefreshResult.NoConnection } val vm = viewModel(repository) backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect { } } vm.refresh() assertEquals("No connection", vm.uiState.value.userMessage) } }
  • 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 and uiState.value would not change. backgroundScope (general knowledge) is a scope from runTest that is cancelled when the test ends.
  • runTest runs coroutine code with a virtual clock, so delay costs no real time (general knowledge).

Instrumented Tests: the DAO

// app/src/androidTest/.../NoteDaoTest.kt (an instrumented test: needs a device or emulator) @RunWith(AndroidJUnit4::class) class NoteDaoTest { private lateinit var db: AppDatabase private lateinit var dao: NoteDao @Before fun createDb() { val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build() dao = db.noteDao() } @After fun closeDb() = db.close() @Test fun insertedNoteIsObserved() = runTest { dao.insert(NoteEntity(text = "Buy milk")) assertEquals(listOf("Buy milk"), dao.observeNotes().first().map { it.text }) } }

(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.

// app/src/androidTest/.../NotesScreenTest.kt (a Compose UI test) class NotesScreenTest { @get:Rule val composeTestRule = createComposeRule() private fun show(state: NotesUiState, onAddNote: (String) -> Unit = {}) { composeTestRule.setContent { NotesScreen( state = state, onAddNote = onAddNote, onDeleteNote = {}, onRefresh = {}, onNewestFirstChange = {}, onMessageShown = {} ) } } @Test fun showsTheNotes() { show(NotesUiState(notes = listOf(Note(1, "Buy milk", 0L)))) composeTestRule.onNodeWithText("Buy milk").assertIsDisplayed() } @Test fun addButtonSendsTheTypedText() { var added: String? = null show(NotesUiState(), onAddNote = { added = it }) composeTestRule.onNodeWithTag("noteInput").performTextInput("Call Ada") composeTestRule.onNodeWithText("Add").performClick() assertEquals("Call Ada", added) } } // In the screen: OutlinedTextField(..., modifier = Modifier.testTag("noteInput"))
  • (docs) createComposeRule() is the one to use when you do not need a specific activity; createAndroidComposeRule gives 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 a contentDescription: it helps users and tests.
  • (docs) The two-clocks warning. Do not mix createComposeRule with runTest in one test: they have separate clocks. If you need coroutine control inside a UI test, the docs point to runComposeUiTest and 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.

@Entity( tableName = "notes", indices = [Index(value = ["remoteId"], unique = true)] ) data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val text: String, val createdAt: Long = System.currentTimeMillis(), val remoteId: Long? = null, @ColumnInfo(defaultValue = "0") val pinned: Boolean = false // new in version 3 ) @Database(entities = [NoteEntity::class], version = 3, exportSchema = true) abstract class AppDatabase : RoomDatabase() { /* ... */ }
import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0") } } // Where the database is built: Room.databaseBuilder(context, AppDatabase::class.java, "notes.db") .addMigrations(MIGRATION_2_3) .build()
  • (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 SQLiteConnection instead of SupportSQLiteDatabase and the package is androidx.room3.
// app/src/androidTest/.../MigrationTest.kt @RunWith(AndroidJUnit4::class) class MigrationTest { private val dbName = "migration-test" @get:Rule val helper = MigrationTestHelper( InstrumentationRegistry.getInstrumentation(), AppDatabase::class.java ) @Test fun migrate2To3_keepsNotesAndAddsPinned() { // 1. Create the database at the OLD version and insert a row with raw SQL helper.createDatabase(dbName, 2).apply { execSQL("INSERT INTO notes (id, text, createdAt) VALUES (1, 'Hi', 0)") close() } // 2. Run the migration; Room validates the resulting schema val db = helper.runMigrationsAndValidate(dbName, 3, true, MIGRATION_2_3) // 3. You check the DATA yourself: the helper only validates the schema db.query("SELECT text, pinned FROM notes WHERE id = 1").use { cursor -> assertTrue(cursor.moveToFirst()) assertEquals("Hi", cursor.getString(0)) assertEquals(0, cursor.getInt(1)) } } }

(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 update twice" 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).
Compared with the Classic UI course
Android Development: Production & Publishing 2 teaches unit tests, instrumented tests, Espresso and Compose UI testing. Here Espresso (for View-based screens) gives way to Compose's own test APIs, and the new material is the ViewModel dispatcher rule, the two-clocks warning, and a worked migration test.

Try It Yourself

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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).

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (two searches, summaries only): the Compose test setup and manifest dependency; 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).
Coming up
Chapter 3 is Background Work: WorkManager, for the jobs that must finish even if the user leaves the app, such as a periodic sync of the notes.