I have the following code:
ViewModel:
private val _prefix = MutableStateFlow("")
val prefix: StateFlow<String> = _prefix
private val _firstName = MutableStateFlow("")
val firstName: StateFlow<String> = _firstName
private val _middleName = MutableStateFlow("")
val middleName: StateFlow<String> = _middleName
private val _lastName = MutableStateFlow("")
val lastName: StateFlow<String> = _lastName
private val _suffix = MutableStateFlow("")
val suffix: StateFlow<String> = _suffix
fun saveContact(
prefix: String,
firstName: String,
middleName: String,
lastName: String,
suffix: String,
) {
_prefix.value = prefix
_firstName.value = firstName
_middleName.value = middleName
_lastName.value = lastName
_suffix.value = suffix
}
}
I call saveContact
from my view once all of the fields relating to the variables are entered.
Here's how I test the above works:
ViewTest:
@Test
fun testView_success() {
lateinit var viewModel: ViewModel
ctr.setContent {
viewModel =
ViewModel(AppDatabase.getDatabase(LocalContext.current).dao)
View(
viewModel = viewModel,
buttonActions = ViewButtonActions(
onNavigateBack = {},
onSave = {},
)
)
}
// Let's make sure that we are displaying the correct view.
ctr.onNodeWithTag(tags.testTag).assertIsDisplayed()
/*
* Personal Details
*/
// Let's now show all fields for each section.
ctr.onNodeWithTag(tags.buttonShowHiddenContentPD).performClick()
// Then we'll insert our text.
ctr.onNodeWithTag(tags.textFieldPrefix).performTextInput(TestData.prefix)
ctr.onNodeWithTag(tags.textFieldFirstName).performTextInput(TestData.firstName)
ctr.onNodeWithTag(tags.textFieldMiddleName).performTextInput(TestData.middleName)
ctr.onNodeWithTag(tags.textFieldLastName).performTextInput(TestData.lastName)
ctr.onNodeWithTag(tags.textFieldSuffix).performTextInput(TestData.suffix)
// Then tap the save button again.
ctr.onNodeWithTag(tags.buttonSave)
// Let's now check to see if all of the text has been passed on.
assertEquals(
TestData.prefix, // is "Mr"
viewModel.prefix.value
)
assertEquals(
TestData.firstName, // "Joe"
viewModel.firstName.value
)
assertEquals(
TestData.middleName, // "Ray"
viewModel.middleName.value
)
assertEquals(
TestData.lastName, // "Bloggs
viewModel.lastName.value
)
assertEquals(
TestData.suffix, // "B.sc
viewModel.suffix.value
)
}
However, I get the following error when I run the test:
junit.framework.ComparisonFailure: expected:<[Mr]> but was:<[]>
at junit.framework.Assert.assertEquals(Assert.java:85)
at junit.framework.Assert.assertEquals(Assert.java:91)
How would I go about testing a MutableStateFlow/StateFlow like this? It seems that my test is not waiting long enough to have the correct data be emitted from the StateFlow.
Thanks