Why ViewModel’s StateFlow is not updating when inside a unit test and is mapped from a repository to UI state using stateIn?

I am testing a ViewModel using a fake repository which uses a StateFlow to store the fake data. This StateFlow is exposed as a normal Flow from the repository. In the ViewModel, I am mapping the received data from repository to a UiState class. When I test the UiState using a local test, I am not getting the updated UiState after adding a new entry i.e. I am stuck on the Loading state and not getting any new updates. Here are the files for viewmodel, repository and the test class.

FakeMedicinesRepository

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class FakeMedicineRepository : MedicineRepository {
private val _medicines = MutableStateFlow<List<Medicine>>(emptyList())
override val allMedicines: Flow<List<Medicine>> = _medicines.asStateFlow()
suspend fun emit(value: List<Medicine>) = _medicines.emit(value)
override suspend fun addMedicine(
name: String,
purchasePrice: BigDecimal,
sellingPrice: BigDecimal
) {
_medicines.update {
it.plus(
Medicine(
it.size + 1L,
name,
purchasePrice,
sellingPrice
)
)
}
}
override suspend fun isNameTaken(name: String): Boolean {
return _medicines.value.any { it.name == name }
}
}
</code>
<code>class FakeMedicineRepository : MedicineRepository { private val _medicines = MutableStateFlow<List<Medicine>>(emptyList()) override val allMedicines: Flow<List<Medicine>> = _medicines.asStateFlow() suspend fun emit(value: List<Medicine>) = _medicines.emit(value) override suspend fun addMedicine( name: String, purchasePrice: BigDecimal, sellingPrice: BigDecimal ) { _medicines.update { it.plus( Medicine( it.size + 1L, name, purchasePrice, sellingPrice ) ) } } override suspend fun isNameTaken(name: String): Boolean { return _medicines.value.any { it.name == name } } } </code>
class FakeMedicineRepository : MedicineRepository {

    private val _medicines = MutableStateFlow<List<Medicine>>(emptyList())
    override val allMedicines: Flow<List<Medicine>> = _medicines.asStateFlow()

    suspend fun emit(value: List<Medicine>) = _medicines.emit(value)

    override suspend fun addMedicine(
        name: String,
        purchasePrice: BigDecimal,
        sellingPrice: BigDecimal
    ) {
        _medicines.update {
            it.plus(
                Medicine(
                    it.size + 1L,
                    name,
                    purchasePrice,
                    sellingPrice
                )
            )
        }
    }

    override suspend fun isNameTaken(name: String): Boolean {
        return _medicines.value.any { it.name == name }
    }
}

MedicinesViewModel

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class MedicinesViewModel(
medicineRepository: MedicineRepository
) : ViewModel() {
val uiState = medicineRepository.allMedicines
.map {
MedicinesUiState.Success(it.map { it.toUiState() })
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = MedicinesUiState.Loading
)
}
</code>
<code>class MedicinesViewModel( medicineRepository: MedicineRepository ) : ViewModel() { val uiState = medicineRepository.allMedicines .map { MedicinesUiState.Success(it.map { it.toUiState() }) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = MedicinesUiState.Loading ) } </code>
class MedicinesViewModel(
    medicineRepository: MedicineRepository
) : ViewModel() {
    val uiState = medicineRepository.allMedicines
        .map {
            MedicinesUiState.Success(it.map { it.toUiState() })
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = MedicinesUiState.Loading
        )
}

MedicinesViewModelTest

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class MedicinesViewModelTest {
private lateinit var repository: FakeMedicineRepository
private lateinit var viewModel: MedicinesViewModel
@Before
fun setup() {
repository = FakeMedicineRepository()
viewModel = MedicinesViewModel(repository)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `when observe medicines should return empty list`() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {
println("State: $it")
}
}
var uiState = viewModel.uiState.value
uiState.shouldBeTypeOf<MedicinesUiState.Loading>()
repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())
// This assertion fails
viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
}
}
</code>
<code>class MedicinesViewModelTest { private lateinit var repository: FakeMedicineRepository private lateinit var viewModel: MedicinesViewModel @Before fun setup() { repository = FakeMedicineRepository() viewModel = MedicinesViewModel(repository) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `when observe medicines should return empty list`() = runTest { backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.uiState.collect { println("State: $it") } } var uiState = viewModel.uiState.value uiState.shouldBeTypeOf<MedicinesUiState.Loading>() repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal()) // This assertion fails viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>() } } </code>
class MedicinesViewModelTest {

    private lateinit var repository: FakeMedicineRepository
    private lateinit var viewModel: MedicinesViewModel

    @Before
    fun setup() {
        repository = FakeMedicineRepository()
        viewModel = MedicinesViewModel(repository)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `when observe medicines should return empty list`() = runTest {
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
            viewModel.uiState.collect {
                println("State: $it")
            }
        }

        var uiState = viewModel.uiState.value
        uiState.shouldBeTypeOf<MedicinesUiState.Loading>()

        repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())

        // This assertion fails
        viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
    }

}

I followed the testing guidance from Testing Kotlin flows on Android. I am using the exact steps as mentioned there, the only difference being they use a SharedFlow in the repository. But I also tried replacing the StateFlow in the fake repository with a SharedFlow with no success.

Looks like I forgot set the Main dispatcher in my unit test that’s why the StateFlow collection wasn’t happening inside the ViewModel. I had seen it being mentioned in the documentation for testing coroutines and to use it whenever we are testing a coroutine which gets started in the viewModelScope as it uses a hardcoded Main dispatcher.

But I ignored it as on the documentation for testing flows then don’t mention it anywhere and just write the test case without setting the dispatcher.

Anyways, here is the final working test file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class MedicinesViewModelTest {
private lateinit var repository: FakeMedicineRepository
private lateinit var viewModel: MedicinesViewModel
@get:Rule
val mainRule = MainDispatcherRule()
@Before
fun setup() {
repository = FakeMedicineRepository()
viewModel = MedicinesViewModel(repository)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `when observe medicines should return empty list`() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {
println("State: $it")
}
}
var uiState = viewModel.uiState.value
uiState.shouldBeTypeOf<MedicinesUiState.Loading>()
repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())
// This assertion is now working
viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
}
}
</code>
<code>class MedicinesViewModelTest { private lateinit var repository: FakeMedicineRepository private lateinit var viewModel: MedicinesViewModel @get:Rule val mainRule = MainDispatcherRule() @Before fun setup() { repository = FakeMedicineRepository() viewModel = MedicinesViewModel(repository) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `when observe medicines should return empty list`() = runTest { backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.uiState.collect { println("State: $it") } } var uiState = viewModel.uiState.value uiState.shouldBeTypeOf<MedicinesUiState.Loading>() repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal()) // This assertion is now working viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>() } } </code>
class MedicinesViewModelTest {

    private lateinit var repository: FakeMedicineRepository
    private lateinit var viewModel: MedicinesViewModel

    @get:Rule
    val mainRule = MainDispatcherRule()

    @Before
    fun setup() {
        repository = FakeMedicineRepository()
        viewModel = MedicinesViewModel(repository)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `when observe medicines should return empty list`() = runTest {
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
            viewModel.uiState.collect {
                println("State: $it")
            }
        }

        var uiState = viewModel.uiState.value
        uiState.shouldBeTypeOf<MedicinesUiState.Loading>()

        repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())

        // This assertion is now working
        viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
    }

}

And, here’s the dispatcher rule which I added in the test file above:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class MedicinesViewModelTest {
private lateinit var repository: FakeMedicineRepository
private lateinit var viewModel: MedicinesViewModel
@get:Rule
val mainRule = MainDispatcherRule()
@Before
fun setup() {
repository = FakeMedicineRepository()
viewModel = MedicinesViewModel(repository)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `when observe medicines should return empty list`() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {
println("State: $it")
}
}
var uiState = viewModel.uiState.value
uiState.shouldBeTypeOf<MedicinesUiState.Loading>()
repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())
// This assertion is now working
viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
}
}
</code>
<code>class MedicinesViewModelTest { private lateinit var repository: FakeMedicineRepository private lateinit var viewModel: MedicinesViewModel @get:Rule val mainRule = MainDispatcherRule() @Before fun setup() { repository = FakeMedicineRepository() viewModel = MedicinesViewModel(repository) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun `when observe medicines should return empty list`() = runTest { backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.uiState.collect { println("State: $it") } } var uiState = viewModel.uiState.value uiState.shouldBeTypeOf<MedicinesUiState.Loading>() repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal()) // This assertion is now working viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>() } } </code>
class MedicinesViewModelTest {

    private lateinit var repository: FakeMedicineRepository
    private lateinit var viewModel: MedicinesViewModel

    @get:Rule
    val mainRule = MainDispatcherRule()

    @Before
    fun setup() {
        repository = FakeMedicineRepository()
        viewModel = MedicinesViewModel(repository)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `when observe medicines should return empty list`() = runTest {
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
            viewModel.uiState.collect {
                println("State: $it")
            }
        }

        var uiState = viewModel.uiState.value
        uiState.shouldBeTypeOf<MedicinesUiState.Loading>()

        repository.addMedicine("Test", 0.toBigDecimal(), 0.toBigDecimal())

        // This assertion is now working
        viewModel.uiState.value.shouldBeTypeOf<MedicinesUiState.Success>()
    }

}

It’s straight from the official documentation on testing coroutines.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật