https://kotlinlang.org logo
Title
p

Pablo

05/04/2022, 8:41 AM
Hello how could I test a function that receives a
Flow<T>
as a parameter and then inside has a
collect { }
? Example
fun doStuff(flow: Flow<String>) {
   scope.launch {
      flow.collect { 
        if(!it in myList) { 
           dataSource.add(it)
        }
      }
   }
}
How would I have this verify that
dataSource.add(it)
? Considering this
myList
is something I can mock too
j

Javier

05/04/2022, 8:43 AM
Checking data source before and after to see if it is adding what you expect
p

Pablo

05/04/2022, 8:44 AM
Yes but how, I mean do I have to do something like :
runBlocking {
   myMethod.doStuff(flowOf("hello"))
}
How would be the pseudo to test it?
j

Javier

05/04/2022, 8:45 AM
You shouldn't need runBlocking, only the new runTest function. It allows advance the time too until the flow is completed
p

Pablo

05/04/2022, 8:46 AM
but do I have to emit the value?
j

Javier

05/04/2022, 8:47 AM
you mean the flowOf?
p

Pablo

05/04/2022, 8:48 AM
yes
j

Javier

05/04/2022, 8:49 AM
Probably you should test multiple scenarios
with empty list, with a unique list, another one to check if the if condition is working and so on