[英]Unit test two api calls within a method
I have a method that makes an API call and if an error occurs it will retry the call with a different instance of the same service API.我有一种方法可以进行 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)
What is the right way to unit test the above code?.对上述代码进行单元测试的正确方法是什么? I tried something like this and it does not seem to work.
我尝试过这样的事情,但它似乎不起作用。
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(..,..,..)
I would test the above the code in below ways, i use mockito kotlin but i think this will help for what you are looking for i:e;我将通过以下方式测试上面的代码,我使用 mockito kotlin 但我认为这将有助于你正在寻找什么,即: right way ( that is subjective):
正确的方式(这是主观的):
@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 )
}
And a test to make sure that newAPIService does not always get called:并进行测试以确保 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 )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.