android - 如何对 LiveData 转换进行单元测试
问题描述
我显然不明白如何在 Transformation 中对业务逻辑进行单元测试。在我的具体情况下,我需要进行测试Transformations.map
,但我想Transformations.switchmap
是一样的。
以下只是我的场景的一个示例,以及我想要实现的目标。
我的视图模型.kt
class MyViewModel: ViewModel() {
private val _sampleLiveDataIwannaTest : MutableLiveData<Int> = MutableLiveData()
val sampleLiveDataIWannaTest: Livedata<Int> = _sampleLiveDataIWannaTest
// ...
val liveDataImNotInterestedIn = Transformations.map(myRepository.streamingData){
streaming->
_sampleLiveDataIwannaTest.postValue(streaming.firstElementValue +streaming.lastElementValue)
streaming
}
// ...
}
和:
val liveDataImNotInteresedIn : LiveData<Foo>
myRepository.streamingData : LiveData<Foo>
myRepository.streamingData
是一个数据源,它唤醒了Transformations.map
我感兴趣的业务逻辑(在 中发布的值_sampleLiveDataIwannaTest
)。在这个特殊的测试中,我不关心其他任何事情。
MyViewModelTest.kt
class MyViewModelTest {
@get:Rule val rule = InstantTaskExecutorRule()
@RelaxedMockK
lateinit var myRepository : MyRepository
@OverrideMockKs
lateinit var sut: MyViewModel
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
}
@Test
fun Transformations_Test(){
sut.liveDataImNotInterestedIn.observeForever{}
// 1)I really don't know how to mock the livedata that returns from
// myRepository.streamingData . Something like this is correct?
// every{myRepository.streamingData}.returns{< LiveData of type Int > }
// 2) I wish to write this kind of test:
//
// assertEquals(5, sampleLiveDataIWannaTest.value)
}
我正在使用 MockK 而不是 Mockito。
解决方案
单元测试代码将如下所示:
class MyViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@RelaxedMockK
lateinit var myRepository : MyRepository
@RelaxedMockK
lateinit var mockedSampleLiveDataIWannaTest : Observer<Int>
@OverrideMockKs
lateinit var sut: MyViewModel
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true)
}
@Test
fun Transformations_Test(){
val expected = (*YOUR EXPECTED DATA HERE FROM REPOSITORY*)
every { myRepository.streamingData() } answers { expected }
sut.sampleLiveDataIWannaTest.observeForever(mockedSampleLiveDataIWannaTest)
verify { myRepository.streamingData() }
verify() { mockedSampleLiveDataIWannaTest.onChanged(Int) }
confirmVerified(myRepository, mockedSampleLiveDataIWannaTest)
}
如果您的存储库正在使用协程,则更every
改为coEvery
和verify
coVerify
了解更多关于 MockK:https ://mockk.io/
推荐阅读
- sqlite - 向表中插入随机行然后删除
- python - 如何使用键在json中获取数组?
- python - 如何从文件夹中读取每个文件并为每个文件创建单独的数据框?
- ios - 如何获取从用户位置到另一个特定位置的路线?
- clojure - 如何解决药物持有率(MPR)问题?
- java - 我使用 StormConfigs startOffsetTime 作为 LatestTime 但如果风暴停止,那么它正在丢失生产者产生的数据
- apache - 在多个 URL 上使用相同的 tomcat 实例
- wordpress - 更新 mailchimp 电子邮件订阅不起作用
- sql - 在 influxDB 中执行了错误的 SQL 查询
- scala - 使用 Scala 在 Spark 中进行空值插补