我有兩個類。第一個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。任何幫助表示讚賞。
你想要測試什麼動作? – maxpovver
getStuffByKey和/或executeGetRequest方法。 – SpaceJump