Mockito:使用模拟方法进行验证

时间:2018-12-04 13:11:22

标签: android unit-testing mockito tdd

我在Mockito中遇到一个奇怪的行为。

测试初始化​​:

private val dao = Mockito.mock(AdDetailsDao::class.java)
    private val offeredResponse = Mockito.mock(AdDetailsRestResponse::class.java) as AdDetailsRestResponse<AdOffered>

此测试成功完成:

@Test
    fun shouldCallWantedAdDetailsAndNotOfferedAdDetails_whenIsNotOfferedAndNotFallback(){
        val handler = AdDetailsHandler(dao, false, false, CompositeDisposable())

        handler.loadAd("some_id")

        verify(dao).getWantedAdDetails(anyString())
        verify(dao, times(0)).getOfferedAdDetails(anyString())
    }

这不是:

@Test
    fun shouldCallOfferedAdDetailsAndWantedAdDetails_whenIsOfferedAndFallbackAndOfferedAdNotExist(){
        val handler = AdDetailsHandler(dao, true, true, CompositeDisposable())

        doReturn(false).`when`(offeredResponse).success
        doReturn(offeredResponse).`when`(dao).getOfferedAdDetails(anyString())

        handler.loadAd("some_id")

        verify(dao).getWantedAdDetails(anyString())
    }

正在测试的方法(请注意,此方法由调度程序在后台执行):

private fun loadWantedTask(id: String): AdDetailsResponse {
        return trackTaskDuration(AnalyticsTagsFabric.Event.AD_DETAILS_LOADED) {
            val response = adDetailsDao.getWantedAdDetails(id)
            AdDetailsWantedResponse(response.advert)
        }
    }

    private fun loadOfferedWithFallbackTask(id: String): AdDetailsResponse {
        return trackTaskDuration(AnalyticsTagsFabric.Event.AD_DETAILS_LOADED) {
            System.out.println("task")
            val response = adDetailsDao.getOfferedAdDetails(id)
            System.out.println("success:" + response.success+ " obj id:"+response)
            if (response.success) {
                System.out.println("in offered")
                AdDetailsOfferedResponse(response.advert)
            }
            else {
                System.out.println("offered else")
                val response = adDetailsDao.getWantedAdDetails(id)
                System.out.println("success:" + response.success+ " obj id:"+response)
                if (response.success) {
                    System.out.println("in wanted")
                    AdDetailsWantedResponse(response.advert)
                } else {
                    System.out.println("in error")
                    AdDetailsErrorResponse(Exception())
                }
            }
        }

测试第二种方法时的输出是:

task
success:false obj id:Mock for AdDetailsRestResponse, hashCode: 991806841
offered else

您可以清楚地看到可以清楚地调用getWantedAdDetails()的地方,但是mockito表示与该模拟物没有交互。

我在做什么错?我以为我不能模拟模拟方法的响应,也不能验证对同一模拟的方法调用,但是我无法弄清楚这是否正确和/或找到解决方案。

1 个答案:

答案 0 :(得分:0)

因此,看起来好像测试在后台执行之前已经完成,因此无法捕获交互。在测试期间强迫这些方法在主线程上运行