【发布时间】:2021-10-21 15:06:44
【问题描述】:
我正在使用改造进行 api 调用,我想编写一个单元测试来检查它是否返回异常。
我想强制改造调用返回异常
数据存储库
class DataRepository @Inject constructor(
private val apiServiceInterface: ApiServiceInterface
) {
suspend fun getCreditReport(): CreditReportResponse {
try {
val creditReport = apiServiceInterface.getDataFromApi() // THIS SHOULD RETURN AN EXCEPTION AND I WANT TO CATCH THAT
return CreditReportResponse(creditReport, CreditReportResponse.Status.SUCCESS)
} catch (e: Exception) {
return CreditReportResponse(null, CreditReportResponse.Status.FAILURE)
}
}
}
ApiService接口
interface ApiServiceInterface {
@GET("endpoint.json")
suspend fun getDataFromApi(): CreditReport
}
我已经为 getCreditReport 编写了一个测试用例,它应该验证失败场景
@Test
fun getCreditReportThrowException() {
runBlocking {
val response = dataRepository.getCreditReport()
verify(apiServiceInterface, times(1)).getDataFromApi()
Assert.assertEquals(CreditReportResponse.Status.FAILURE, response.status)
}
}
所以要让上面的测试用例通过,我需要强制网络调用抛出异常
请推荐
谢谢 回复
【问题讨论】:
-
您可以通过在 GET 方法中提供错误的路由来做到这一点,但是有一种更好的方法来测试存储库,方法是创建存储库一个接口,然后每当您想测试存储库时,您可以通过 FakeRepository 实现,它会让测试更容易。
-
你能分享一个例子吗
标签: android unit-testing kotlin retrofit