0

我有一个客户端将向 GraphQL 端点发出请求,如下所示

import com.apollographql.apollo.ApolloClient

internal class GraphQLClient(apolloClient:ApolloClient, retryStrategy:RetryStrategy){

   override fun <D : Operation.Data, T, V : Operation.Variables> mutate(mutate: Mutation<D, T, V>): Flow<T> {
        val response = apolloClient.mutate(mutate)
        val responseFlow = response.toFlow()
        return responseFlow.map<Response<T>, T> {
            it.data ?: throw ResponseError("Data Null")
        }.retryWhen { cause, attempt ->
            retryStrategy.retry(cause,attempt)
        }
    }
}

我正在使用MockWebServer测试上述内容以创建模拟响应

  • JUnit 测试
  • 使用Turbine进行测试Flow
  • 我正在尝试验证对于成功的更新请求,重试逻辑不会被执行
   @Test
    fun `GIVEN a successful update, THEN don't retry`() = runBlocking {
        val server = MockWebServer()
        val mockResponse = MockResponse()
        //Successful response in json format. It's the correct format.
        mockResponse.setBody(readFileFromResources("mock_success_response.json"))
        mockResponse.setResponseCode(200)
        server.enqueue(mockResponse)
        server.start()

        val url = server.url("http://loalhost:8080")
        val apolloClient: ApolloClient = ApolloClient.builder()
            .okHttpClient(OkHttpClient())
            .serverUrl(url.toString())
            .addCustomAdapters()
            .build()

        val retryStrategy = mockk<RetryStrategy>()
        val graphQLClient = GraphQLClient(apolloClient)

        //The mutation of intrest
        val mutation = UpdateMutation(
            SomeInput(
                "123"
            )
        )

        //note how i haven't mocked anything related to retry strategy cause this test doesn't need that

        graphQLClient.mutate(mutation).test {
            verify(exactly = 0) { retryStrategy.retry(any(),any()) }
            expectComplete()
        }

        server.shutdown()

    }

但是,我的测试失败了 app.cash.turbine.AssertionError: Expected complete but found Error(MockKException)

在堆栈跟踪的下方,我可以看到有关缺少answer一些重试逻辑相关事物的抱怨但我认为这是引发上述异常的原因,实际上,甚至不应该执行 Caused by: io.mockk.MockKException: no answer found for: RetryStrategy(#1).isError(com.apollographql.apollo.exception.ApolloNetworkException: Failed to execute http call)

P:S-我可能在这里也测试了太多,但很想了解发生了什么

我尝试过的事情如果有影响但没有改变错误,只需将响应更改为空字符串。这让我觉得它可能与响应数据无关,

谢谢

4

1 回答 1

1

问题出在这条线上

 val url = server.url("http://loalhost:8080")

MockServer 不期望主机或端口

 val url = server.url("/somepath")
于 2020-12-02T22:42:26.880 回答