我有一个用例,我试图从另一个包中实例化一个内部公共静态final类。我试图这样做,以便我可以模拟对单元测试的响应。我们可以使用模拟服务器,但是,我只想在这种情况下使用模拟对象来提高速度和控制测试。以下是以下代码段:
public class Http {
private final HttpClient client;
@Inject
Http(HttpClient client) {
this.client = client;
}
public Http.Response get(Http.Request request) {
try {
Http.Response response = this.getResponse(this.client.execute(this.createHttpGet(request)));
return response;
} catch (IOException var4) {
throw new RuntimeException(var4);
} catch (URISyntaxException var5) {
throw new RuntimeException(var5);
}
}
private Http.Response getResponse(HttpResponse httpResponse) throws IOException {
Http.Response response = new Http.Response(httpResponse.getStatusLine().getStatusCode());
response.setMessageBody(EntityUtils.toString(httpResponse.getEntity()));
return response;
}
public static final class Response {
private final int statusCode;
private ImmutableMap<String, String> headers;
private String message;
private String messageBody;
Response(int statusCode) {
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
public Map<String, String> getHeaders() {
return this.headers;
}
void setHeaders(Map<String, String> headers) {
this.headers = ImmutableMap.builder().putAll(headers).build();
}
public String getMessage() {
return this.message;
}
void setMessage(String message) {
this.message = message;
}
public String getMessageBody() {
return this.messageBody;
}
void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public String toString() {
return String.format("HttpResponse{statusCode=%d, headers=%s, message='%s', messageBody='%s'}", this.statusCode, this.headers, this.message, this.messageBody);
}
}
}
答案 0 :(得分:0)
您的Http.Response
构造函数需要公开才能从另一个包中实例化。
此处,由于其可见性为default
,因此您只能从同一个包中实例化它。
您似乎需要它用于测试目的。如果您不想更改可见性,则可以在与Http
类相同的包中的测试类中创建一个类,仅用于实例化Responses
。