Skip to content

Instantly share code, notes, and snippets.

@ppamorim
Created July 23, 2019 17:49
Show Gist options
  • Save ppamorim/a3e82d8e379cc8918bd963f3d79654d0 to your computer and use it in GitHub Desktop.
Save ppamorim/a3e82d8e379cc8918bd963f3d79654d0 to your computer and use it in GitHub Desktop.
Mock OkHttpClient with MockWebServer
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
inline fun mockServer(
address: String,
response: String,
responseCode: Int,
run: (OkHttpClient) -> Unit) {
val server = MockWebServer()
val mockedResponse = MockResponse()
mockedResponse.setResponseCode(responseCode)
mockedResponse.setBody(response)
server.enqueue(mockedResponse)
server.start()
val httpUrl: HttpUrl = server.url(address)
val okHttpClient = OkHttpClient.Builder().addInterceptor(object: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
request = request.newBuilder()
.url(httpUrl)
.build()
return chain.proceed(request)
}
}).build()
run(okHttpClient)
server.takeRequest()
server.shutdown()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment