首页 > 解决方案 > 如何对 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。

标签: androidunit-testingkotlinandroid-livedatamockk

解决方案


单元测试代码将如下所示:

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改为coEveryverifycoVerify

了解更多关于 MockK:https ://mockk.io/


推荐阅读