-
-
Save gianpaolof/11ba07016f77f676e6df0b2725686305 to your computer and use it in GitHub Desktop.
Android : Mock Response with Retrofit & OkHttp
This file contains hidden or 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
class LoginInterceptor: Interceptor{ | |
override fun intercept(chain: Interceptor.Chain): Response { | |
//If requested endpoint matched to targeted endpoint, we will return an mocked response. | |
if (chain.request().url.toUri().toString().endsWith("fake-login")) { | |
val responseString = "OUR_JSON_RESPONSE_FROM_ASSET_OR_OTHER_SOURCE" | |
return chain.proceed(chain.request()) | |
.newBuilder() | |
.code(200) | |
.protocol(Protocol.HTTP_2) | |
.message(responseString) | |
.body( | |
responseString | |
.toByteArray() | |
.toResponseBody( | |
"application/json".toMediaTypeOrNull() | |
) | |
) | |
.addHeader("content-type", "application/json") | |
.build() | |
} else { | |
//Skip the interception. | |
return chain.proceed(chain.request()) | |
} | |
} | |
} | |
object RetrofitProvider { | |
//Return a lazy instance of OkHttp client | |
private val myHttpClient: OkHttpClient by lazy { | |
val ins = OkHttpClient().newBuilder() | |
.connectTimeout(1, TimeUnit.MINUTES) | |
.readTimeout(1, TimeUnit.MINUTES) | |
.writeTimeout(1, TimeUnit.MINUTES) | |
.retryOnConnectionFailure(true) | |
//Adding our LoginInterceptor only on Debug mode only | |
if (BuildConfig.DEBUG){ | |
ins.addInterceptor(LoginInterceptor()) | |
} | |
ins.build() | |
} | |
//Public access point for Mock API Service | |
fun getMockAPI(): MockAPIEndpoint = retrofitInstance.create(MockAPIEndpoint::class.java) | |
//Return a lazy Retrofit instance | |
private val retrofitInstance: Retrofit by lazy { | |
Retrofit.Builder() | |
.baseUrl("https://rommansabbir/api/v2/") | |
.client(myHttpClient) | |
.build() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment