2015-09-28 104 views
3

我是Retrofit 2.0的新手,我想問一下使用此方法進行單元測試的最佳方法,尤其是對於異步請求。Retrofit 2.0使用本地JSON進行Android單元測試

我發現了一篇關於它的好文章here,我對使用本地JSON靜態文件進行單元測試感興趣,因爲它在我看來會更快,並不總是需要Internet連接,但它不會當我在Retrofit 2.0上實現它時工作。在Retrofit 2.0中可以做到這一點嗎?

或者也許有人可以在這裏幫助我很好的參考資料,或者有關如何做這些單元測試的一些很好的例子嗎?

對不起,我的英語不好。

回答

3

下面是使用OkHttp Interceptor實施的改進2的參考方法的快速翻譯。我給了它一個快速測試,但沒有太深。讓我知道你是否有問題。

public class LocalResponseInterceptor implements Interceptor { 

    private Context context; 

    private String scenario = null; 

    public LocalResponseInterceptor(Context ctx) { 
     this.context = ctx; 
    } 

    public void setScenario(String scenario) { 
     this.scenario = scenario; 
    } 

    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request(); 
     URL requestedUrl = request.url(); 
     String requestedMethod = request.method(); 

     String prefix = ""; 
     if (this.scenario != null) { 
      prefix = scenario + "_"; 
     } 

     String fileName = (prefix + requestedMethod + requestedUrl.getPath()).replace("/", "_"); 
     fileName = fileName.toLowerCase(); 

     int resourceId = context.getResources().getIdentifier(fileName, "raw", 
       context.getPackageName()); 

     if (resourceId == 0) { 
      Log.wtf("YourTag", "Could not find res/raw/" + fileName + ".json"); 
      throw new IOException("Could not find res/raw/" + fileName + ".json"); 
     } 

     InputStream inputStream = context.getResources().openRawResource(resourceId); 

     String mimeType = URLConnection.guessContentTypeFromStream(inputStream); 
     if (mimeType == null) { 
      mimeType = "application/json"; 
     } 

     Buffer input = new Buffer().readFrom(inputStream); 

     return new Response.Builder() 
       .request(request) 
       .protocol(Protocol.HTTP_1_1) 
       .code(200) 
       .body(ResponseBody.create(MediaType.parse(mimeType), input.size(), input)) 
       .build(); 
    } 
} 

這個攔截添加到自定義OkHttpClient -

OkHttpClient okHttpClient = new OkHttpClient(); 
    okHttpClient.interceptors().add(new LocalResponseInterceptor(context)); 

其中context是一個Android Context

和客戶端添加到您的改造 -

Retrofit retrofit = new Retrofit.Builder() 
     .baseUrl("https://api.github.com/") 
     .addConverterFactory(GsonConverterFactory.create()) 
     .client(okHttpClient) 
     .build(); 
+0

我可以看你怎麼用這個在單元測試?我試圖使用Robolectric,並得到了這個錯誤'線程中的異常「OkHttp Dispatcher」java.lang.NullPointerException'。 – Michael