首页 > 解决方案 > 测试失败案例不会与android抛出错误

问题描述

我正在尝试为 kotlin Coroutine 进行单元测试,但是当我尝试对这样的失败案例进行测试时:它失败了

@Test
    fun getFailure() {

        testCoroutineRule.runBlockingTest {

            val error = Error()

            whenever(apiService.getApiResponse(key)).thenThrow(error)
            
           verify(observer).onChanged(Resource.error(null,error))

        }

    }

它给了我一个错误参数不同!通缉:

Argument(s) are different! Wanted:
observer.onChanged(
    Resource(status=ERROR, data=null, error=java.lang.Error)
);
Actual invocation has different arguments:
observer.onChanged(
    Resource(status=LOADING, data=null, error=null)
);

这是获取在 viewmodel 中声明的 api 数据的函数的方式

fun getResponse(key:String) = liveData(Dispatchers.IO) {
        emit(Resource.loading(data = null))
        try {
            emit(Resource.success(data = apiService.getApiResponse(key)))
        }catch (exception:Exception){
            emit(Resource.error(data = null,error = exception))
        }

    }

以及我如何在测试前设置模拟

 @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)

        DaggerViewModelComponent.builder()
            .apiModule(ApiModuleTest(apiService))
            .build()
            .inject(mainViewModel)

        mainViewModel.getResponse(key).observeForever(observer)
    }

标签: androidunit-testingkotlinmockitocoroutine

解决方案


推荐阅读