0Pricing
Jetpack Compose Academy · Aula

Testando ViewModels e Flows

Teste a lógica unitariamente com despachantes de teste.

Testando ViewModels e Flows é uma aula grátis de Jetpack Compose Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Jetpack Compose Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Jetpack Compose Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Test Logic Without the UI

A ViewModel holds your screen logic, so you can test it directly with plain JUnit. No emulator or rendering needed, which makes these tests fast. ⚡

Arrange, Act, Assert

ViewModel tests follow a simple rhythm: create the ViewModel, call a function, then assert the new state. Keep each test focused on one behavior.

val vm = CounterViewModel()
vm.increment()
assertEquals(1, vm.count)

The Coroutine Challenge

Many ViewModels launch coroutines, which run on Dispatchers.Main. In tests there is no main looper, so you must swap in a test dispatcher instead.

StandardTestDispatcher

A StandardTestDispatcher gives you full control over coroutine timing. Tasks queue up and run only when you advance the virtual clock.

val dispatcher = StandardTestDispatcher()

Replace the Main Dispatcher

Use Dispatchers.setMain before each test to inject your test dispatcher, then call resetMain afterward to leave global state clean.

Dispatchers.setMain(dispatcher)

runTest

Wrap suspending test bodies in runTest. It provides a coroutine scope with a virtual clock so delays resolve instantly, not in real seconds.

@Test fun loads() = runTest {
    // suspend calls run here
}

Quick Check

Your ViewModel launches coroutines on the main dispatcher. What lets a unit test control their execution?

Advancing the Clock

With a StandardTestDispatcher, queued coroutines wait. Call advanceUntilIdle inside runTest to run them all, then check the final state.

advanceUntilIdle()
assertEquals(Loaded, vm.uiState.value)

Testing a StateFlow

ViewModels often expose a StateFlow. Its current snapshot lives in .value, so you can read and assert it directly after advancing the clock.

assertEquals(0, vm.count.value)

Collecting Flow Emissions

To capture a sequence of emissions, the Turbine library makes Flow testing easy with awaitItem, asserting each value as it arrives.

vm.events.test {
    assertEquals(Saved, awaitItem())
}

Fake Your Dependencies

Inject a fake repository that returns canned data. This keeps tests fast and lets you simulate success and error paths without a real network.

val vm = NewsViewModel(FakeRepo())

Clean Teardown

Always pair setMain with resetMain in your teardown. Leaving a test dispatcher installed can leak into and break other tests in the suite.

@After fun tearDown() {
    Dispatchers.resetMain()
}

Recap: ViewModels & Flows

Test logic without UI by swapping in a test dispatcher, running code in runTest, and asserting StateFlow values. Fast, focused, reliable tests. 🏁

Perguntas Frequentes

A aula “Testando ViewModels e Flows” é grátis?

Sim — o texto completo de “Testando ViewModels e Flows” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Jetpack Compose Academy, atualize para CoddyKit PRO. O curso de Jetpack Compose Academy inclui 4 aulas no total.

O que vou aprender em “Testando ViewModels e Flows”?

Teste a lógica unitariamente com despachantes de teste. Você pratica Jetpack Compose Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Jetpack Compose Academy?

Nenhuma experiência prévia é necessária. Jetpack Compose Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Testando ViewModels e Flows”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Jetpack Compose Academy?

Sim. Cada aula de Jetpack Compose Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. createComposeRule e Localizadores
  2. Verificações e Execução de Ações
  3. Semântica e Etiquetas de Teste
  4. Testando ViewModels e Flows
← Voltar para Jetpack Compose Academy