【问题标题】:How can I mock complex (url) API with Retrofit如何使用 Retrofit 模拟复杂的(url)API
【发布时间】:2019-03-18 12:15:14
【问题描述】:

我需要做一些本网站描述的事情:https://blog.davidmedenjak.com/android/2016/11/22/mocking-api-calls.html1

我需要使用一些 json 文件来模拟我的 API,实现我自己的 OkHttp 拦截器。我可以用简单的 url 来做到这一点,但是如果 url 更复杂,我怎么能做到这一点,例如:

/hello/world/{myName}/{mySurname}

?

在我的自定义拦截器中,url 已经“编译”了,但我需要根据他们的文件名读取我的 json 文件,所以我需要 {myName} 和 {mySurname} 作为字符串。我想我应该阅读 url 的注释,但我找不到任何这样的例子。

我的源代码和上面的网站类似,我有我的API.kt:

internal interface API {
    @GET("hello/world/{myName}/{mySurname}")
    fun hello(
        @Path(value = "myName") name: String,
        @Path(value = "mySurname") surname: String
    ): Observable...
}

还有我的 ServiceFactory.kt,我在其中实现了我的自定义拦截器:

val httpClient = OkHttpClient.Builder()
httpClient.interceptors().add(Interceptor { chain ->
    // here I have my request and response
    // here the request URL is already compiled, for example: /hello/world/steve/jobs
})

所以我认为我应该阅读实现我自己的 ConverterFactory 的 url 注释:

retrofit
    .client(httpClient.build())
    .addConverterFactory(MoshiConverterFactory.create())
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .build()
    .create<API>(API::class.java)

感谢任何帮助!谢谢大家!

【问题讨论】:

  • 你能分享一些你的代码吗?

标签: android api retrofit okhttp moshi


【解决方案1】:

如果您能提供更多关于您正在尝试做什么的背景信息,那将会很有帮助。据我了解,您不需要仅用于测试的自定义拦截器。您可以使用MockWebServer,按顺序排列请求并按顺序测试响应。 MockWebServer 有一个 takeRequest() 方法,您可以使用该方法断言标头、URL、请求参数等。

文档可以在这里找到:https://github.com/square/okhttp/tree/master/mockwebserver

【讨论】:

  • 我不想启动新的本地服务器。我只需要使用模拟 json 文件作为特定风味的响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 2022-01-24
相关资源
最近更新 更多