0

我有一个进行 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(..,..,..)
4

1 回答 1

2

我将通过以下方式测试上面的代码,我使用 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 )
            }
于 2021-01-25T07:40:27.517 回答