tezvyn:

Unit test a ViewModel exposing StateFlow in a local JVM test

Source: developer.android.comintermediate

Tests coroutine hygiene and flow collection strategy. A strong answer covers injecting a TestDispatcher, using runTest, collecting emissions in a background scope, and asserting states.

Tests structured concurrency in tests and StateFlow semantics. A strong answer hits four things: inject a TestDispatcher so the ViewModel runs on controllable threads; wrap the test in runTest to skip delays; collect emissions in a background scope or with Turbine; assert the latest value or the emission sequence. Red flag: hardcoding Dispatchers.Main without a Main dispatcher override, using runBlocking instead of runTest, or forgetting that StateFlow deduplicates rapid equal values.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Unit test a ViewModel exposing StateFlow in a local JVM test · Tezvyn