Java:如何单元测试使用REST服务的抽象类

时间:2016-10-28 10:17:14

标签: java unit-testing mockito

我有两节课。第一个ServiceConsumer是一个抽象类,用于初始化其构造函数中的服务器设置。它具有使用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进行单元测试。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

赞成合成而不是继承就是答案。 ServiceConsumer提供了要调用的功能。但是没有理由将该功能放在基类中。将此移至其自己的类,使用接口抽象该功能,并让ServiceClient依赖于该接口。

您的代码显示了类设计的明确警告标志:您的派生类正在调用基类的非抽象保护方法。