What\'s the best way to mock a server for testing when using the square retrofit framework.
Potential ways:
Create a new retrofit client and set it
Mocking api calls with Retrofit is now even easier with Mockinizer which makes working with MockWebServer really straight forward:
import com.appham.mockinizer.RequestFilter
import okhttp3.mockwebserver.MockResponse
val mocks: Map = mapOf(
RequestFilter("/mocked") to MockResponse().apply {
setResponseCode(200)
setBody("""{"title": "Banana Mock"}""")
},
RequestFilter("/mockedError") to MockResponse().apply {
setResponseCode(400)
}
)
Just create a map of RequestFilter and MockResponses and then plug it into your OkHttpClient builder chain:
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.mockinize(mocks) // <-- just plug in your custom mocks here
.build()
You don't have to worry about configuring MockWebServer etc. Just add your mocks all the rest is done by Mockinizer for you.
(Disclaimer: I am the author of Mockinizer)