我正在传递一个服务网址,它将获取一个json。我使用对象映射器将json映射到响应类。我将如何模拟url以在测试用例中调用实际服务?
public String QUOTE_SUMMARY_URL = "http://localhost:8181/omnesys_sb/quote";
@SuppressWarnings("deprecation")
public Quotesummary getQuoteSummary(final String urlString) throws JsonParseException, JsonMappingException, IOException {
String line, jsonString = null;
HttpURLConnection httpURLConnection = null;
ObjectMapper mapper = new ObjectMapper();
String urlStr = urlString != null ? urlString : QUOTE_SUMMARY_URL;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Accept", "application/json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
Quotesummary quoteSummary = mapper.readValue(jsonString, Quotesummary.class);
System.out.println(""+mapper.writerWithDefaultPrettyPrinter().writeValueAsString(quoteSummary));
return quoteSummary;
}