Hi all, how do you guys test a StateFlow in Androi...
# test
m
Hi all, how do you guys test a StateFlow in Android, for example, a ViewModel?
with LiveData, it was easy, as we could observer forever but with a StateFlow, I don’t see any way of doing something similar
k
take a look at
Turbine
by square. It's fantastic. https://github.com/cashapp/turbine
also you'll probably want to be looking at
runBlocking
for your tests
...and also avoiding
viewModelScope
. Testing becomes a bit easier if you inject a scope into the viewmodel via dependency injection and then implement
CoroutineScope
via interface delegation
let me dig you up an example.
Copy code
class MyViewModel @Inject constructor(
    @Named("viewModelScope") scope: CoroutineScope
) : ViewModel(), CoroutineScope by scope {

    override fun onCleared() {
        super.onCleared()
        cancel()
    }
}

@Test fun testFoo() = runBlocking { // this: CoroutineScope
    val viewModel = MyViewModel(this)

    viewModel.someFlow.test { ... }
}
m
thanks @kevin.cianfarini! I tried but I get this:
Copy code
java.lang.NoSuchMethodError: app.cash.turbine.FlowTurbineKt.test-f_gJSvk$default(Lkotlinx/coroutines/flow/Flow;DLkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object;
k
That's strange. Did you add is as a
testImplementstion
? Also you can try asking questions over at #squarelibraries
m
yep I did
ah OK, I can ask there, thanks!