Professional software engineering requires automated tests to guarantee that code changes do not introduce regressions. Android architecture separates tests into two primary buckets: Local Unit Tests (run quickly on your host machine's JVM) and Instrumented Tests (run on an actual Android device or emulator).
We test our ArticlesViewModel without needing any Android device by mocking the repository using Mockk and testing StateFlow emissions using Turbine:
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ArticlesViewModelTest {
private val testDispatcher = StandardTestDispatcher()
private val mockRepository = mockk<ArticleRepository>()
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher) // Replace Main thread with test dispatcher
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun loadArticles_successfulResponse_updatesUiState() = runTest {
// Given
val dummyArticles = listOf("Android 15 Architecture", "Compose State")
coEvery { mockRepository.fetchArticles() } returns dummyArticles
// When
val viewModel = ArticlesViewModel(mockRepository)
testDispatcher.scheduler.advanceUntilIdle()
// Then
assertEquals(dummyArticles, viewModel.uiState.value.articles)
assertEquals(false, viewModel.uiState.value.isLoading)
}
}
Testing Composables is fast and declarative using Compose Test Rules:
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import org.junit.Rule
import org.junit.Test
class CounterScreenTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun buttonClick_incrementsCounter() {
// Render composable
composeTestRule.setContent {
CounterWidget()
}
// Verify initial state
composeTestRule.onNodeWithText("Total Clicks: 0").assertExists()
// Perform click interaction
composeTestRule.onNodeWithText("Total Clicks: 0").performClick()
// Verify updated state
composeTestRule.onNodeWithText("Total Clicks: 1").assertExists()
}
}
Broaden your foundational and advanced Android application development skills across our curriculum:
Test asynchronous ViewModel state emissions with Turbine and Coroutines.
Test SQLite DAO queries with Room.inMemoryDatabaseBuilder.
Use createComposeRule to verify Composable click interactions.
Run ./gradlew test and connectedCheck automatically on pull requests.