首页 > 解决方案 > 如何使用 viewmodel + livedata 进行单元测试改造 api 调用?

问题描述

我刚刚了解了 Android 单元测试。我想用 viewmodel + livedata 对我的练习项目实施单元测试 API 改造调用。这是视图模型类之一。

class NextMatchViewModel(league : League, application: Application): AndroidViewModel(application) {

// get idLeague passing for call getNextMatch()
private val _idLeague = MutableLiveData<League>()
private val idLeague: LiveData<League>
    get() = _idLeague

// next match liveData
private val _nextMatch = MutableLiveData<List<Match>>()
val nextMatch: LiveData<List<Match>>
    get() = _nextMatch

init {
    //get _idLeague value from argument(SafeArgs)
    _idLeague.value = league

    getNextMatch()
}

private fun getNextMatch() {

    idLeague.value?.idLeague?.let {
        LeagueApi.retrofitService.getNextMatch(it).enqueue(object : Callback<MatchResponse>{
            override fun onFailure(call: Call<MatchResponse>, t: Throwable) {
                Log.d(TAG, t.message!!)
            }

            override fun onResponse(call: Call<MatchResponse>, response: Response<MatchResponse>) {
                _nextMatch.value = response.body()?.events
                Log.d(TAG, "success")
            }

        })
    }
}

companion object {
    private val TAG = NextMatchViewModel::class.java.simpleName
}

}

标签: androidunit-testing

解决方案


实际上,您不需要对 API 请求进行单元测试!当您需要访问您的存储或网络时,您需要为您的代码提供一些仪器测试。


推荐阅读