问题描述
我有一个调用 API 的方法,如果发生错误,它将使用同一服务 API 的不同实例重试调用。
var getResponse = myApi?.getCodeApi()
if (getResponse?.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// retrying with instance of service with a different token
getResponse = newMyApiService?.getCodeApi()
}
checkResponse(getResponse)
对上述代码进行单元测试的正确方法是什么?我试过这样的事情,但似乎不起作用。
whenever(myAPi.getCodeApi()).thenReturn(properResponse)
val errorResponse : Response<DataModel> = mock()
whenever(response.code()).thenReturn(HttpsURLConnection.HTTP_UNAUTHORIZED)
whenever(myAPi.getCodeApi()).thenReturn(errorResponse)
test.callMethod()
assertValues(..,..,..)
解决方法
我会以下面的方式测试上面的代码,我使用 mockito kotlin 但我认为这将有助于你正在寻找的东西 i:e; 正确的方式(这是主观的):
@Test
fun `retry with newMyApiService when myAPI returns HTTP_UNAUTHORIZED`() {
myApi.stub {
on {
getCodeApi() } doReturn Erorr_Response_Model
}
newMyApiService.stub {
on {
getCodeApi() } doReturn Response_Model
}
test.callMethod();
verify(newMyApiService,times(1)). getCodeApi()
Assertions.assert(..Above Response_Model )
}
还有一个确保 newAPIService 不会总是被调用的测试:
@Test
fun `myApi should return the valid result without retrying`() {
myApi.stub {
on {
getCodeApi() } doReturn SuccessModel
}
test.callMethod();
verify(newMyApiService,times(0)). getCodeApi()
verify(myApi,times(1)). getCodeApi()
Assertions.assert(..SuccessModel )
}