2016-10-28 75 views
0

我有兩個類。第一個ServiceConsumer是一個在其構造函數中初始化服務器設置的抽象類。它保護了使用REST服務的方法。Java:How to Unit測試使用REST服務的抽象類

public abstract class ServiceConsumer { 

public ServiceConsumer(String configFilePath) { 
    initConfigSuccessful = false; 
    initConfiguration(configFilePath); 
} 

protected RestResponse executeGetRequest(String urlString) { 
    if (!initConfigSuccessful) { 
     return RestResponseFactory.createErrorResponse("Initialization error!"); 
    } 

    try { 
     HttpClient httpClient = HttpClientBuilder.create().build(); 
     HttpGet getRequest = new HttpGet(urlString); 
     byte[] authentication = Base64.getEncoder().encode((username + ":" + password).getBytes()); 
     getRequest.setHeader("Authorization", "Basic " + new String(authentication)); 

     HttpResponse response = httpClient.execute(getRequest); 
     HttpEntity entity = response.getEntity(); 
     InputStream responseStream = entity.getContent(); 
     String responseString = StringHelper.getFileContent(responseStream); 
     JsonElement responseElement = new JsonParser().parse(responseString); 
     int responseCode = response.getStatusLine().getStatusCode(); 

     if (responseElement == null || responseElement.isJsonNull()) { 
      return RestResponseFactory.createResponse(responseCode); 
     } else if (responseElement.isJsonObject()) { 
      return RestResponseFactory.createResponse(responseCode, responseElement.getAsJsonObject()); 
     } else if (responseElement.isJsonArray()) { 
      return RestResponseFactory.createResponse(responseCode, responseElement.getAsJsonArray()); 
     } 
    } catch (Exception e) { 
     return RestResponseFactory.createErrorResponse(e); 
    } 
    return RestResponseFactory.createErrorResponse("Unexpected error occured!"); 
    } 
} 

第二類ServiceClient延伸ServiceConsumer和調用該方法的超構造和方法。

public class ServiceClient extends ServiceConsumer { 

private static String configFilePath = "/server-config.json"; 

public ServiceClient() { 
    super(getConfigFilePath()); 
} 

public RestResponse getStuffByKey(String key) { 
    RestResponse restResponse = executeGetRequest(getBasicUrl() + "/rest/api/2/stuff/" + key); 
    return restResponse; 
    } 
} 

我不知道如何單元測試這與Mockito。任何幫助表示讚賞。

+0

你想要測試什麼動作? – maxpovver

+0

getStuffByKey和/或executeGetRequest方法。 – SpaceJump

回答

2

繼承遺產就是答案。 ServiceConsumer正在提供要調用的功能。但是沒有理由將該功能放在基類中。把它移到它自己的類中,用接口抽象這個功能,並讓它依賴於這個接口。

您的代碼顯示了類設計的明確警告標誌:您的派生類正在調用基類的非抽象受保護方法。

+0

謝謝你的回答,但我不確定我的理解。你能更具體一點我必須做的嗎? – SpaceJump