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<RequestFilter, MockResponse> = 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)
https://jsonplaceholder.typicode.com/
https://reqres.in/
If you want to test customized response payload, the above two might not suit your requirement, then you can try postman mock server. It's quite easy to set up and flexible to define your own request and response payload.
https://learning.getpostman.com/docs/postman/mock_servers/intro_to_mock_servers/ https://youtu.be/shYn3Ys3ygE
You can also use something like Webservermock from Squareup! --> https://github.com/square/okhttp/tree/master/mockwebserver
For me the custom Retrofit Client is great because of flexibility. Especially when you use any DI framework you can fast and simple turn on/off mock. I am using custom Client provided by Dagger also in unit and integration tests.
Edit: Here you find example of mocking retrofit https://github.com/pawelByszewski/retrofitmock
Testing JSON deserialization to your objects (presumably with TypeAdapters
?) seems like a separate problem that require separate unit tests.
I use version 2 personally. It affords type-safe, refactor-friendly code that can be easily debugged and altered. After all, what good is declaring your API as interfaces if you aren't creating alternate versions of them for testing! Polymorphism for the win.
Another option is using a Java Proxy
. This is actually how Retrofit (currently) implements its underlying HTTP interaction. This will admittedly require more work, but would allow for much more dynamic mocks.