Writing Unit Tests for Kotlin Stateflow in Android

37 views Asked by At

I'm trying out the new Kotlin Stateflow with Android and I'm writing Unit tests for it.

class MainViewmodel @Inject constructor() : ViewModel() {

    private val _screenState:MutableStateFlow<ScreenState> = MutableStateFlow(ScreenState())
    val screenState:StateFlow<ScreenState> = _screenState

    private var expenditureTypes:List<String> = listOf()

    init {
        getExpenditureTypes()
    }

    private fun getExpenditureTypes() {
        viewModelScope.launch {
//This line is the repository call to get the expenditure types
            getExpendituresTys {
                getExpenditureCategories()
            }
        }
    }

    private fun getExpenditureCategories() {
        viewModelScope.launch {
            val expenditureCategory:String = expenditureTypes.find { it == _screenState.value.expenditureType }!!
//This line is the repository call to get the expenditure categories
            getExpendituresCts(expenditureCategory) {categories ->
                _screenState.update {
                    it.copy(categories = categories)
                }
            }
        }
    }


Basically what I'm doing is like, In the viewmodel init block I'm getting the expenditure types. After getting the expenditure types I'm getting the expenditure categories based on the default value from the ScreenState class. The issue is when i'm trying to update the variable expenditureTypes it is not updating and I'm using this variable in the upcoming lines and It is throwing null pointer exception in the Tests.

While running the app this issue is not occurring but while writing UTs this issue is happening.

I guess I'm missing something obvious. To fix this issue I have removed the init block and made that getExpenditureTypes() function as a public one. and then this issue is resolved. Can anyone point out what is wrong in this code snippet

0

There are 0 answers