Square retrofit server mock for testing

前端 未结 11 1373
栀梦
栀梦 2020-12-07 06:54

What\'s the best way to mock a server for testing when using the square retrofit framework.

Potential ways:

  1. Create a new retrofit client and set it

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 07:35

    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)

提交回复
热议问题