0

几天来,我一直在尝试测试我的视图模型,但没有成功。

这是我的视图模型:

class AdvertViewModel : ViewModel() {

    private val parentJob = Job()

    private val coroutineContext: CoroutineContext
        get() = parentJob + Dispatchers.Default

    private val scope = CoroutineScope(coroutineContext)

    private val repository : AdvertRepository = AdvertRepository(ApiFactory.Apifactory.advertService)

    val advertContactLiveData = MutableLiveData<String>()

    fun fetchRequestContact(requestContact: RequestContact) {
        scope.launch {
            val advertContact = repository.requestContact(requestContact)
            advertContactLiveData.postValue(advertContact)
        }
    }
}

这是我的存储库:

class AdvertRepository (private val api : AdvertService) : BaseRepository() {

    suspend fun requestContact(requestContact: RequestContact) : String? {

        val advertResponse = safeApiCall(
            call = {api.requestContact(requestContact).await()},
            errorMessage = "Error Request Contact"
        )

        return advertResponse
    }
}

这是我的视图模型测试:

@RunWith(JUnit4::class)
class AdvertViewModelTest {
    private val goodContact = RequestContact(...)

    private lateinit var advertViewModel: AdvertViewModel

    private var observer: Observer<String> = mock()

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setUp() {
        advertViewModel = AdvertViewModel()
        advertViewModel.advertContactLiveData.observeForever(observer)
    }

    @Test
    fun fetchRequestContact_goodResponse() {
        advertViewModel.fetchRequestContact(goodContact)

        val captor = ArgumentCaptor.forClass(String::class.java)

        captor.run {
            verify(observer, times(1)).onChanged(capture())
            assertEquals("someValue", value)
        }
    }
}

方法 mock() :

inline fun <reified T> mock(): T = Mockito.mock(T::class.java)

我收到了这个错误:

需要但未调用:observer.onChanged(); -> 在 com.vizzit.AdvertViewModelTest.fetchRequestContact_goodResponse(AdvertViewModelTest.kt:52) 实际上,与此模拟的交互为零。

我不明白如何检索我的查询结果。

4

1 回答 1

1

您需要编写一个OneTimeObserver来观察来自ViewModel

class OneTimeObserver<T>(private val handler: (T) -> Unit) : Observer<T>, LifecycleOwner {
    private val lifecycle = LifecycleRegistry(this)

    init {
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
    }

    override fun getLifecycle(): Lifecycle = lifecycle

    override fun onChanged(t: T) {
        handler(t)
        lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }
}

之后,您可以编写扩展函数:

fun <T> LiveData<T>.observeOnce(onChangeHandler: (T) -> Unit) {
    val observer = OneTimeObserver(handler = onChangeHandler)
    observe(observer, observer)
}

比你可以检查我从一个项目中获得的这个ViewModelLiveData来检查你在调用方法后(何时)发生了什么。

至于您的错误,它只是说该onChanged()方法从未被调用过。

于 2019-12-20T09:51:03.537 回答