Lesson 27: Testing Your App: Basics of Unit Testing
Testing Your App: Basics of Unit Testing
You've built a real app across the last 26 lessons. Now let's make sure it actually keeps working as you change it, with automated tests.
Where tests live
Android Studio creates a src/test/ folder for fast, JVM-only unit tests (no emulator needed) and a separate src/androidTest/ folder for instrumented tests that need a real device or emulator. Start with unit tests — they run in seconds and cover most of what you need at this stage.
Testing a simple function
class TaskDtoMapperTest {
@Test
fun `toTask correctly maps completed field to isDone`() {
val dto = TaskDto(userId = 1, id = 1, title = "Test", completed = true)
val task = dto.toTask()
assertEquals(true, task.isDone)
assertEquals("Test", task.title)
}
}Note the backtick-wrapped test name — Kotlin allows spaces and full sentences in function names inside backticks, purely for tests, making test output far more readable than camelCaseNamesLikeThis.
Testing a ViewModel
class TaskListViewModelTest {
@Test
fun `addTask increases the task count`() = runTest {
val fakeDao = FakeTaskDao()
val viewModel = TaskListViewModel(fakeDao)
viewModel.addTask("New task")
assertEquals(1, fakeDao.getAllTasks().first().size)
}
}Notice FakeTaskDao() — this is exactly why lesson 18's architecture split matters: because the ViewModel depends on a TaskDao interface, not a concrete Room database, we can substitute a simple in-memory fake for testing, with no real database or emulator required.
What's worth testing as a beginner
Don't try to test everything. Focus on: data mapping functions (like toTask()), ViewModel logic (like addTask), and anything with a bug you've already hit once — a regression test for a real bug is one of the highest-value tests you can write.
Next: Lesson 28 — preparing your app's icon, name, and theme for release.