这是我的仓库
interface TrendingRepository{
fun getTrendingRepos()
测试类
@RunWith(JUnit4::class)
class TrendingViewModelTest {
private val trendingRepository = mock(TrendingRepository::class.java)
private var trendingViewModel = TrendingViewModel(trendingRepository)
@Test
fun testWithNoNetwork() {
trendingViewModel.isConnected = false
verify(trendingRepository, never()).getTrendingRepos()
}
@Test
fun testWithNetwork() {
trendingViewModel.isConnected = true
verify(trendingRepository, never()).getTrendingRepos()
}
}
TrendingViewModel
fun fetchTrendingRepos() {
if (isConnected) {
loadingProgress.value = true
compositeDisposable.add(
trendingRepository.getTrendingRepos().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
run {
loadingProgress.value = false
},
{ error ->
loadingProgress.value = false
}
)
)
}
这两个测试都通过了,但是TrendingViewModel
仅在有活动网络getTrendingRepos()
时才调用isConnected = true
答案 0 :(得分:2)
在验证之前,您应该调用要测试的功能:
@RunWith(JUnit4::class)
class TrendingViewModelTest {
private val trendingRepository = mock(TrendingRepository::class.java)
private var trendingViewModel = TrendingViewModel(trendingRepository)
@Test
fun testWithNoNetwork() {
trendingViewModel.isConnected = false
trendingViewModel.fetchTrendingRepos()
verify(trendingRepository, never()).getTrendingRepos()
}
@Test
fun testWithNetwork() {
trendingViewModel.isConnected = true
trendingViewModel.fetchTrendingRepos()
verify(trendingRepository, times(1)).getTrendingRepos()
}
}