对方法中的两个 api 调用进行单元测试
Unit test two api calls within a method
我有一个调用 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 )
}
我有一个调用 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 )
}