Hi all! I want to write a unit test for this code ...
# compose
m
Hi all! I want to write a unit test for this code block and I’m sending multiple values to the State class, is it possible to collect values of the state? Like; values[0] == Loading values[1] == Success
r
Hey 👋 I think you might be interested in the Turbine library https://github.com/cashapp/turbine
m
Hi @Rafal! I guess, Turbine is for Flow testing but this class is State. I’m not sure to turbine works for this.
a
Use
snapshotFlow {}
to get a flow from snapshot state changes
👍 1
Then you can use turbine or whatever other testing strategy you like to validate state change outputs of other operations under test
r
Oh sorry I missread this one a little. Did you consider to change it a little? So instead of having a method that mutates the state, you could have a method that returns a flow of the view states
Then you could easly test it with the Turbine library
m
I think you could do something like this with snapshotFlow and turbine
Copy code
snapshotFlow { viewModel.uiState }.test {
    expectItem().shouldBeInstanceOf< UiState.Loading>
    expectItem().shouldBeInstanceOf<UiState.Success>
}
Perhaps a different assertion is in order (I dont remember which one you would use with junit)
m
Hi @Adam Powell! I try to understand to
snapshotFlow
but when I start to collect it, it just prints
0
. What is the missing point? The sample from the doc https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#snapshotFlow(kotlin.Function0)
a
`snapshotFlow`'s flow never terminates and you are calling it in a
runBlocking
. Your
Snapshot.withMutableSnapshot
block is not running.
Snapshots notify observers of changes when the snapshot commits. If you had an observer running concurrent with that
Snapshot.withMutableSnapshot
block, the observer would see an initial value of
0
followed by
3
as
3
is the value of
state
when the snapshot commits. If more changes happened and committed before the collector coroutine could resume, the collector would see only the latest value. State never guarantees that you see every value assigned and committed, only the latest available when the observer runs.
m
Could you share a small code sample, please? Because the test finish before the check the assertion. @Adam Powell