Mock OkHttp responses at Interceptor level
Add this in your root build.gradle
file (not your module build.gradle
file):
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
Then, add the library to your module build.gradle
dependencies {
implementation 'com.github.faruktoptas.okmocker:okmocker-writer:1.1.2'
implementation 'com.github.faruktoptas.okmocker:core:1.1.2'
androidTestImplementation 'com.github.faruktoptas.okmocker:okmocker-reader:1.1.2'
androidTestImplementation 'com.github.faruktoptas.okmocker:core:1.1.2'
}
if (BuildConfig.DEBUG) {
okHttpClientBuilder.addInterceptor(OkMockerWriteInterceptor(SdCardWriter(context)))
}
Run the app. Responses from the server will be saved to the external storage. Don't forget to grant WRITE_EXTERNAL_STORAGE
permission. (If your app doesn't need WRITE_EXTERNAL_STORAGE
permission you can add this permission to a specific build variant that you run the tests)
Pull saved responses to assets under androidTest
folder.
adb pull /sdcard/Android/data/[PACKAGE_NAME]/cache/okmocker app/src/androidTest/assets
okHttpClientBuilder
.addInterceptor(OkMockerReadInterceptor(AssetsReader(InstrumentationRegistry.getContext().assets)))
Step 1 is the same as above
Pull responses to the build variant that will use mocking.
adb pull /sdcard/Android/data/[PACKAGE_NAME]/cache/okmocker app/src/[BUILD_VARIANT]/assets
Use application context
okHttpClientBuilder
.addInterceptor(OkMockerReadInterceptor(AssetsReader(applicationContext.assets)))
class MyReader : OkMockerReader {
override fun read(chain: Interceptor.Chain): ResponseBody {
val path = chain.request().url().toString().toFileName()
val content = when (path) {
"https://PATH" -> "[{\"name\":\"path\"}]"
else -> "[{\"name\":\"else\"}]"
}
return ResponseBody.create(MediaType.parse("application/json"), content)
}
override fun canRead(request: Request) = true // Always return true
}
Pass the reader to the interceptor
.addInterceptor(OkMockerReadInterceptor(MyReader()))