[英]I have problem how to make jUnit tests for consume REST api method
我需要对该代码进行JUnit / Mockito测试,但我不知道如何启动它。 我找不到答案或任何帮助,所以我做了一个新话题。 有人可以写一个我应该怎么做的例子吗?
@Override
public List<CurrencyList> currencyValuesNBP() {
ArrayList<CurrencyList> currencyListArrayList = new ArrayList<>();
try {
URL url = new URL("http://api.nbp.pl/api/exchangerates/tables/A?format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String jsonOutput = bufferedReader.readLine();
httpURLConnection.disconnect();
ObjectMapper objectMapper = new ObjectMapper();
currencyListArrayList = objectMapper.readValue(jsonOutput, new TypeReference<ArrayList<CurrencyList>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return currencyListArrayList;
}
我建议两种方法来测试您的方法:
ionut
提到的模拟服务器,例如WireMock 。 设置服务器后,您可以调用测试的方法并对其返回值执行所需的检查。 这种方法的缺点-需要创建服务器,并且如果在方法实现中更改了URL,则必须更改单元测试代码。 @Override public List<CurrencyList> currencyValuesNBP() { List<CurrencyList> currencyListArrayList = new ArrayList<>();
try {
URL url = new URL("http://api.nbp.pl/api/exchangerates/tables/A?format=json");
ObjectMapper objectMapper = new ObjectMapper();
currencyListArrayList = objectMapper.readValue(handleRESTApiCall(url), new TypeReference<ArrayList<CurrencyList>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return currencyListArrayList;
}
public String handleRESTApiCall(URL url) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String jsonOutput = bufferedReader.readLine();
httpURLConnection.disconnect();
return jsonOutput;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
您现在可以测试,使用Mockito
一个URL
例如, handleRESTApiCall
无需服务器实例。 缺点是需要在handleRESTApiCall
的输出上添加其他handleRESTApiCall
,以获取您要验证的对象。 但是,您将受益于拥有一个基本的周期性解决方案来处理代码中的REST api调用。
引用:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.