Square retrofit server mock for testing

前端 未结 11 1374
栀梦
栀梦 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

    Adding to the answer by @Alec, I have extended the mock client to get the response directly from a text file in asset folder depending on the request URL.

    Ex

    @POST("/activate")
    public void activate(@Body Request reqdata, Callback callback);
    

    Here the mock client, understands that the URL being fired is activate and looks for a file named activate.txt in the assets folder. It reads the content from assets/activate.txt file and sends it as response for the API.

    Here is the extended MockClient

    public class MockClient implements Client {
        Context context;
    
        MockClient(Context context) {
            this.context = context;
        }
    
        @Override
        public Response execute(Request request) throws IOException {
            Uri uri = Uri.parse(request.getUrl());
    
            Log.d("MOCK SERVER", "fetching uri: " + uri.toString());
    
            String filename = uri.getPath();
            filename = filename.substring(filename.lastIndexOf('/') + 1).split("?")[0];
    
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            InputStream is = context.getAssets().open(filename.toLowerCase() + ".txt");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String responseString = new String(buffer);
    
            return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", responseString.getBytes()));
        }
    }
    

    For a detailed explanation you can checkout my blog
    http://www.cumulations.com/blogs/13/Mock-API-response-in-Retrofit-using-custom-clients

提交回复
热议问题