Android Testing: Unit Testing, Mockk & Compose UI Tests

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

Local Unit Test with Mockk & Turbine (Testing ViewModels)

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

Jetpack Compose UI Testing (createComposeRule)

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()
    }
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between app/src/test and app/src/androidTest?

`app/src/test` holds Local Unit Tests that execute on your computer's local Java Virtual Machine (runs in milliseconds). `app/src/androidTest` holds Instrumented Tests that require an actual Android device or emulator to test hardware APIs and full UI workflows.

Q2. Why do we use Dispatchers.setMain() in tests?

By default, `Dispatchers.Main` relies on the Android OS Looper, which does not exist in local desktop JVM unit tests. Calling `Dispatchers.setMain(testDispatcher)` swaps it with a test scheduler that you can control manually.

Q3. What is Robolectric?

Robolectric is a framework that allows you to run Android framework tests (like Activity lifecycles or View inflation) on your desktop JVM without needing to boot a slow emulator.

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

ViewModel & StateFlow Testing

Test asynchronous ViewModel state emissions with Turbine and Coroutines.

Room In-Memory Testing

Test SQLite DAO queries with Room.inMemoryDatabaseBuilder.

Jetpack Compose UI Testing

Use createComposeRule to verify Composable click interactions.

CI/CD Automated Test Pipelines

Run ./gradlew test and connectedCheck automatically on pull requests.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!