You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单元测试中强制Retrofit接口调用抛出异常以验证失败逻辑

实现方案

核心思路

单元测试不需要构造真实Retrofit实例,直接Mock ApiServiceInterface 接口实例,指定调用getDataFromApi()时主动抛出异常即可触发异常捕获分支。
前置条件:测试类中注入到DataRepository的apiServiceInterface必须是Mock框架生成的模拟实例,不能是Retrofit动态生成的真实实例,否则Mock规则不会生效。

方案1:使用Mockito实现

需引入org.mockito.kotlin:mockito-kotlin依赖适配Kotlin协程,Mockito版本建议升级到4.0+原生支持suspend方法Mock。
在原有测试用例中新增异常触发规则即可:

@Test
fun getCreditReportThrowException() {
    runBlocking {
        // 新增规则:调用api方法时主动抛出异常
        whenever(apiServiceInterface.getDataFromApi()).thenThrow(RuntimeException("模拟网络请求异常"))
        
        val response = dataRepository.getCreditReport()
        verify(apiServiceInterface, times(1)).getDataFromApi()
        Assert.assertEquals(CreditReportResponse.Status.FAILURE, response.status)
    }
}

方案2:使用MockK实现(Kotlin生态更常用)

如果项目使用MockK框架,对应写法如下,注意suspend方法需要用协程专属的Mock/验证方法:

@Test
fun getCreditReportThrowException() {
    runBlocking {
        // 新增规则:调用suspend方法时抛出异常
        coEvery { apiServiceInterface.getDataFromApi() } throws RuntimeException("模拟网络请求异常")
        
        val response = dataRepository.getCreditReport()
        // 协程方法需要用coVerify验证
        coVerify(exactly = 1) { apiServiceInterface.getDataFromApi() }
        Assert.assertEquals(CreditReportResponse.Status.FAILURE, response.status)
    }
}

内容的提问来源于stack exchange,提问作者BRDroid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:09:02