Member-only story
Day 25: Testing StateFlow in ViewModel โ From Unit Tests to UI Events
Why Should You Test StateFlow?
If youโre managing state with StateFlow, your ViewModel becomes the brain of your UI.
Testing it ensures:
โ
Your UI state behaves as expected
โ
Events are emitted correctly
โ
You avoid regressions and random bugs
What Weโll Test
Letโs take yesterdayโs LoginViewModel as an example:
data class LoginFormState(
val email: String = "",
val password: String = "",
val isValid: Boolean = false
)fun onEmailChange(...) // Updates state
fun onPasswordChange(...)
fun onLoginClick() // Emits one-time event (ex: Snackbar)Step 1: Add Test Dependencies
// In build.gradle (test)
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
testImplementation("junit:junit:4.13.2")Step 2: Test StateFlow Updates
@ExperimentalCoroutinesApi
class LoginViewModelTest {
private val testDispatcher = StandardTestDispatcher()
private lateinit var viewModel: LoginViewModel
@Before
fun setup() {
Dispatchers.setMain(testDispatcher)โฆ