我需要为该代码进行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;
}
答案 0 :(得分:0)
我建议两种方法来测试您的方法:
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
的输出上添加额外的样板,以获得想要验证的对象。但是,您将受益于拥有一个基本的周期性解决方案来处理代码中的REST api调用。
推荐: