即使没有调用方法,mockito never()也会被调用吗?

时间:2019-09-23 05:08:39

标签: android unit-testing mockito

这是我的仓库

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

1 个答案:

答案 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()
    }
}