Issue
Could someone provide an advanced example of using the new TestScope
and TestScope.launch
while testing with coroutines?
It seems like in the new kotlinx.coroutines.test
release they've added somewhat called TestScope
to the library. Also, they've deprecated the old TestCoroutineDispatcher
and told to use TestScope.runTests
instead, however, they didn't add much documentation on how to use it. Everything I could find is this.
Can anyone provide me with some extra examples of usage in different scenarios?
Solution
I could also fix this problem with @Joffrey mentioned at the comment.
You only need to use runTest { }
to use coroutine scope at the test code. By using runTest { }
you can use TestScope
inside the block with this
.
In my case, there was a flow function at the viewModel something like this. It was running inside the viewModelScope
.
fun getFriendDataWithFlow() {
viewModelScope.launch {
repository.loadFriendsWithFlow()
...
}
}
And I should test this at my test code, and I used it like this.
@ExperimentalCoroutinesApi
@Before
fun setup() {
Dispatchers.setMain(StandardTestDispatcher())
}
@ExperimentalCoroutinesApi
@Test
fun temp() {
runTest {
viewModel.getFriendDataWithFlow()
}
}
All I did was add runTest { }
block, and add coroutine code inside the block. And it worked for me.
My test coroutine dependency was "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0-RC"
.
Answered By - Lee WonJoong
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.