android - 如何使用 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
}
}
解决方案
实际上,您不需要对 API 请求进行单元测试!当您需要访问您的存储或网络时,您需要为您的代码提供一些仪器测试。
推荐阅读
- sqlite - SQLite:如何将 memvfs 扩展嵌入到合并中?
- python - Python - 从文本文件访问列表中的项目
- vb.net - 这个 RSA 有什么问题,为什么加密/解密的结果不同?
- opengl - EGL 是否需要 GPU?
- bash - 对 package.json 中的 docker 镜像名称进行 Grep
- c# - Polly WaitAndRetry 与最终异常什么都不做
- spring - 如何使用 ThymLeaf 将实体分配给表单中的另一个实体?
- c# - CA1062 未在 .Net Standard 2.0 类库上进行评估
- java - 拒绝名称空间仅在文件扩展名(最后一个点之后的部分)上有所不同的 WSDL 是否合法?
- pyinstaller - 了解 pyinstaller