I have a use case where I am trying to instantiate an inner public static final class from a different package. I am trying to do this so that I can mock the Response to unit testing. We can use a mock server, however, I just want to use a mock object for this case for speed and more controlled testing. Here is the code snippet below:
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);
}
}
}
Your Http.Response
constructor needs to be public to be instantiated from another package.
Here, because its visibility is default
, you can only instantiate it from the same package.
You seem to need it for testing purposes. If you don't want to change the visibility, you can create a class in your testing classes in the same package as your Http
class only for instantiating Responses
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.