KotlinLeaner
03/15/2023, 10:40 PMrunTest
. I have a simple viewModel
class LoadingViewModel(
private val ioDispatcher: CoroutineDispatcher,
) : ViewModel() {
var xyz by mutableStateOf(false)
fun checkXyz() {
viewModelScope.launch {
delay(1000L)
xyz = true
}
}
}
more code in š§µ@OptIn(ExperimentalCoroutinesApi::class)
class LoadingViewModelTest {
private val subject by lazy {
spyk(LoadingViewModel(UnconfinedTestDispatcher()))
}
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
}
@Test
fun `xyz - when method called then should assign value on xyz`() = runTest {
subject.checkXyz()
verify {
<http://subject.xyz|subject.xyz> = true
}
}
}
junit4
with kotlin 1.8.10
Verification failed: call 1 of 1: LoadingViewModel(#3).setXyz(eq(true))) was not called.
Calls to same mock:
1) LoadingViewModel(#3).checkXyz()
2) LoadingViewModel(#3).getTag(androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY)
3) LoadingViewModel(#3).setTagIfAbsent(androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY, androidx.lifecycle.CloseableCoroutineScope@2d5580f6)
delay
it working fine.Joffrey
03/15/2023, 11:58 PMxyz
immediately, so why do you think you can immediately verify that it has been set?ephemient
03/16/2023, 12:03 AMviewModelScope
doesn't use the TestCoroutineScheduler
, so this isn't testable anywayJoffrey
03/16/2023, 12:05 AMephemient
03/16/2023, 12:07 AMadvanceTimeBy
can move virtual time to allow you to observe the post-delay effects, but not in this case because viewModelScope
is totally separateJoffrey
03/16/2023, 12:14 AMlaunch
internally, but also it's given a different test dispatcher than the one from the runTest
call, so I don't think it would work even if subject
used its ioDispatcher
property in the launch
.KotlinLeaner
03/16/2023, 10:22 AMwhy do you think you can immediately verify that it has been set?
I am just testing the function and see in the document delay
can we skip by using runTest
.ioDispatcher
inside my viewModelScope
but still I am getting error.
fun checkXyz() {
viewModelScope.launch(ioDispatcher) {
delay(1000L)
xyz = true
}
}
what else I need to add in test?