Powermock v3.8 和 RESUME 事件有一个示例。我使用这个事件来展示如何验证 livedata 值
#build.gradle
dependencies {
...
testImplementation 'org.robolectric:robolectric:3.8'
testImplementation "org.powermock:powermock-module-junit4:2.0.2"
testImplementation "org.powermock:powermock-module-junit4-rule:2.0.2"
testImplementation "org.powermock:powermock-api-mockito2:2.0.2"
testImplementation "org.powermock:powermock-classloading-xstream:1.6.4"
...
}
#CustomViewModel.kt
class CustomViewModel() : ViewModel(), LifecycleObserver {
private val _outputData = MutableLiveData<Boolean>()
val outputData: LiveData<Boolean> = _outputData
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
//TODO action
outputData.value = true
}
}
#CustomViewModelTest.kt
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
import org.powermock.core.classloader.annotations.PowerMockIgnore
import org.powermock.modules.junit4.PowerMockRunner
import org.powermock.modules.junit4.PowerMockRunnerDelegate
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(PowerMockRunner::class)
@PowerMockRunnerDelegate(RobolectricTestRunner::class)
@PowerMockIgnore("org.mockito.*", "org.robolectric.*", "androidx.*")
@Config(manifest = Config.NONE)
class CustomViewModelTest {
@Mock
lateinit var observer: Observer<in Boolean>
@Before
fun beforeTest() {
MockitoAnnotations.initMocks(this)
}
@Test
@Config(sdk = [Build.VERSION_CODES.O])
fun `do an action on resume event`() {
val vm = spy(CustomViewModel())
vm.outputData.observeForever(observer)
vm.testLifecycleEvent(Lifecycle.Event.ON_RESUME)
verify(vm).onResume()
verify(observer).onChange(true)
}
}
fun LifecycleObserver.testLifecycleEvent(lifecycleEvent: Lifecycle.Event) {
val lifecycleOwner = Mockito.mock(LifecycleOwner::class.java)
val lifecycleRegistry = LifecycleRegistry(lifecycleOwner)
this.bindToLifecycle(lifecycleRegistry)
lifecycleRegistry.handleLifecycleEvent(lifecycleEvent)
}
fun LifecycleObserver.bindToLifecycle(lifecycle: Lifecycle) {
lifecycle.addObserver(this)
}