Created
July 23, 2019 17:49
-
-
Save ppamorim/a3e82d8e379cc8918bd963f3d79654d0 to your computer and use it in GitHub Desktop.
Mock OkHttpClient with MockWebServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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