Square retrofit server mock for testing

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

    I decided to try method 1 as follows

    public class MockClient implements Client {
    
        @Override
        public Response execute(Request request) throws IOException {
            Uri uri = Uri.parse(request.getUrl());
    
            Log.d("MOCK SERVER", "fetching uri: " + uri.toString());
    
            String responseString = "";
    
            if(uri.getPath().equals("/path/of/interest")) {
                responseString = "JSON STRING HERE";
            } else {
                responseString = "OTHER JSON RESPONSE STRING";
            }
    
            return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", responseString.getBytes()));
        }
    }
    

    And using it by:

    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient(new MockClient());
    

    It works well and allows you to test your json strings without having to contact the real server!

提交回复
热议问题