I’m not sure what I’m doing wrong here but I can’t...
# coroutines
l
I’m not sure what I’m doing wrong here but I can’t make a private flow to collect in a unit test, tried multiple different things by pausing/resuming dispatchers, here’s the setup: 🧵
Copy code
internal class ViewModel @Inject constructor(
  ...
  private val dispatcher: Dispatchers,
) : ViewModel() {
  val listContent = MutableLiveData<PropertyGroupDisplayInfo>()
  private var propertyChangedValue = MutableStateFlow("")

  init {
    viewModelScope.launchMain<PropertiesEditV2ViewModel> {
      propertyChangedValue
        .drop(1)
        .debounce(DEBOUNCE_DELAY)
        .mapNotNull(::validatePropertyInline)
        .collect {
          listContent.value = it
        }
    }
fun handleTextPropertyUpdate(property: String, value: String) {
  viewModelScope.launch(dispatcher.default) { propertyChangedValue.emit(value) }
}
  }
and my test is simple as setting up mocks and calling the
viewmodel
public method that is emitting a value to the flow
Copy code
@Test
fun testNameHere() = runBlockingTest {
  ...
  viewModel.run {
    handleTextPropertyUpdate(Contact.EMAIL, "test@")
    verify(validateEmailUseCase).invoke("test@")
 } 

}
I’m using a
TestDispatcher
in tests as well, debugging I can see that handleTextPropertyUpdate is called and the coroutine
viewModelScope.launch(dispatcher.default) { propertyChangedValue.emit(value) }
too, but the flow never collects in tests not sure what is missing
also I’m using a test rule to override the main dispatcher with a testDispatcher
if I remove the
debounce
operator it works… I can’t figure out why nw
r
Did you try
advanceTimeBy(DEBOUNCE_DELAY)
before the verify?
l
@Robert Williams yeap all sort of combinations of advancing a dispatcher pausing it, resuming it and etc
r
And how about with a
Thread.sleep(DEBOUNCE_DELAY)
?
l
not yet I will give this a try, but I tried something that would be similar, a
delay
in the
runBlockingTest
block of the test
r
That's what I'm getting at - if the
sleep
works but the
advanceTimeBy
doesn't it's a problem with how you've set up the dispatchers. If neither works it's a problem with the flow setup