【问题标题】:Unit test two api calls within a method在一个方法中对两个 api 调用进行单元测试
【发布时间】:2021-01-25 07:11:25
【问题描述】:

我有一个调用 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(..,..,..)

【问题讨论】:

    标签: android mockito powermockito android-unit-testing


    【解决方案1】:

    我将通过以下方式测试上面的代码,我使用 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 )
                }
    

    【讨论】:

    • 我的 newAPIService 正在通过 Koin 在单元测试和方法中注入。在通过单元测试进行测试时,使用 newAPIService 的第二个 API 调用总是返回 null,从而导致我的单元测试失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多