gpt4 book ai didi

java - 我在如何为使用 REST api 方法进行 jUnit 测试时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:45 25 4
gpt4 key购买 nike

我需要对该代码进行 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;
}

最佳答案

我建议使用两种方法来测试您的方法:

  1. 使用专用测试服务器 - 在您的 JUnit 类中,创建一个服务器实例,该实例在接收您的方法使用的 URL(“http://api.nbp.pl/api/exchangerates/tables/A?format=json”)时将返回固定对象。您可以使用模拟服务器,例如 WireMock ,如ionut所述。设置服务器后,您可以调用测试方法并对其返回值执行所需的检查。这种方法的缺点 - 需要创建服务器,并且如果在方法实现中更改 URL,则必须更改单元测试代码。
  2. 将您的方法重构为核心方法和特定使用方法,并测试核心方法 - 将您的代码重构为以下内容:

@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 调用的基本重复解决方案。

引用文献:

关于java - 我在如何为使用 REST api 方法进行 jUnit 测试时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com