A guide to testing Android ViewModels without Android framework dependencies by extracting UI logic into a pure Kotlin UIModel class. The pattern injects a CoroutineScope into the UIModel constructor, allowing tests to pass backgroundScope from runTest instead of using Dispatchers.setMain(). Key techniques include using fun interfaces for use cases to create simple lambda-based fakes without mock libraries, a createSut helper pattern for test setup, and using UnconfinedTestDispatcher for synchronous-looking tests. The post also explains why WhileSubscribed(5_000) is preferred over Eagerly for resource efficiency, and covers gotchas like StateFlow conflation and advanceUntilIdle() not processing backgroundScope tasks.

10m read timeFrom proandroiddev.com
Post cover image
Table of contents
Testing a pure-Kotlin UIModel without android framework dependencies. No Dispatchers.setMain(), no Robolectric, no mocks.How the Tests LookFunctional Interfaces Use Cases Make Fakes TrivialThe createSut PatternWhy backgroundScopeGet Felix Leyva’s stories in your inboxWhy We Need a Collector at AllWhy WhileSubscribed instead of EagerlySome things to watch out for!UnconfinedTestDispatcher vs StandardTestDispatcherStateFlow Is ConflatedonStart Fires at createSut TimeTurbineWhat You Get
1 Comment

Sort: