在 Java 中编写单元测试并跳过方法中的某些代码行的最佳实践是什么?
我有java代码只需执行以下步骤:
- 从url获取json响应(我想跳过这个,而是使用预定义的变量进行测试)
- 检查一些条件(我想执行单元测试)
- 执行put方法来终止应用程序使用rest-api(我想跳过这个,因为我不想在测试条件时杀死任何应用程序)
这是我想要执行单元测试的方法:
public void checkYarnApplications() throws IOException {
// Get json object from yarn rest-api
ObjectMapper mapper = new ObjectMapper();
URL getJsonUrl1 = new URL(getUrlAddress());
Map<String,Object> map1 = mapper.readValue(getJsonUrl1,Map.class);
JSONObject j = new JSONObject(map1);
// Initialize stringbuilder to build slack message
StringBuilder stringBuilder = new StringBuilder();
// Iterate through number of existing yarn application
for (int i = 0; i < j.getJSONObject("apps").getJSONArray("app").length(); i++){
JSONObject name = j.getJSONObject("apps")
.getJSONArray("app")
.getJSONObject(i);
String state = name.get("state").toString();
// Check if application is in Running state
if (state.equals("RUNNING")){
// Get elapsed time for each running application and convert it to hour
int elapsed_time = name.getInt("elapsedTime")/3600000;
// Get application name
String app_name = name.get("name").toString();
// Get application queue_name
String queue_name = name.get("queue").toString();
// Get application user_name
String user_name = name.get("user").toString();
// Check if pyspark applications last longer than specified time in config.properties
if (app_name.startsWith("pyspark-shell") && elapsed_time > getSparkCheckTime()){
String app_id = name.get("id").toString();
String infoMessageSpark = "pyspark application " + app_id + " has been killed because it takes longer than " + getSparkCheckTime() + " hours";
logger.info(infoMessageSpark);
logger.info(name.toString());
// Kill yarn application
URL url = new URL(String.format("%s%s/state?user.name=atlasapp",getUrlAddress(),app_id));
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"state\": \"KILLED\"}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
// Add info message to slackmessage string builder
stringBuilder.append(infoMessageSpark);
stringBuilder.append("\n");
}
// Check if self_bi applications last longer than specified time in config.properties
else if (!queue_name.equals("yarn-system") && !queue_name.equals("hudi") && !queue_name.equals("hepsistream") &&
!app_name.equals("Bzip2Hdfs") && !user_name.equals("spark") && !user_name.equals("yarn-ats") &&
!app_name.startsWith("pyspark-shell") && !queue_name.equals("llap") && elapsed_time > getappCheckTime()){
String app_id = name.get("id").toString();
String infoMessageSb = queue_name + " application, " + app_id + " has been killed because it takes longer than "
+ getappCheckTime() + " hours. Elapsed Time:" + elapsed_time;
logger.info(infoMessageSb);
logger.info(name.toString());
// Kill yarn application
URL url = new URL(String.format("%s%s/state?user.name=atlasapp",getUrlAddress(),app_id));
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"state\": \"KILLED\"}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
// Add info message to slackmessage string builder
stringBuilder.append(infoMessageSb);
stringBuilder.append("\n");
}
// Check if any application except hudi, llap last longer than specified time in config.properties and send them to slack channel
else if (!queue_name.equals("hudi") && !queue_name.equals("llap") && !queue_name.equals("hepsistream") &&
!queue_name.equals("yarn-system") && !user_name.equals("yarn-ats") &&
!app_name.startsWith("pyspark-shell") && !app_name.equals("Bzip2Hdfs") && !user_name.equals("spark") &&
elapsed_time > getCheckTime()){
logger.info("Application_id: " + name.get("id").toString() + " is running longer than " + getCheckTime() + " hours");
String textMessage ="Elapsed time: " + elapsed_time + " hours" + ", " +
"Application_Id: " + name.get("id").toString() + ", " +
"Username: " + name.get("user").toString() + ", " +
"Queuename:" + name.get("queue").toString() + ", " +
"Usage:" + name.get("clusterUsagePercentage").toString();
stringBuilder.append(textMessage);
stringBuilder.append("\n");
}
}
}
}
这里我想使用一些预定义的json字符串,它将等于我使用 http 连接作为响应收到的字符串。并且只想检查 if - else-if 条件是否正常工作。如果满足条件,还想跳过某些代码行来终止某些应用程序。所以我只想实现一些assertequal方法来比较infoMessage字符串(您可以在我的代码中看到)。 我找到了一些模拟完整方法的mockito方法,但在这里我想跳过方法内部的一些代码行,但我找不到任何有关此要求的示例。任何帮助和指导将不胜感激。
谢谢。
I have java code simply do below steps:
- Getting json response from url (I would like to skip this and instead use pre defined variable for test purposes)
- Check some conditions (which i would like to perform unit test)
- Execute put method to kill applications using rest-api (I would like to skip this because I do not want to kill any application while testing conditions)
Here is my method which I would like to perform unit test:
public void checkYarnApplications() throws IOException {
// Get json object from yarn rest-api
ObjectMapper mapper = new ObjectMapper();
URL getJsonUrl1 = new URL(getUrlAddress());
Map<String,Object> map1 = mapper.readValue(getJsonUrl1,Map.class);
JSONObject j = new JSONObject(map1);
// Initialize stringbuilder to build slack message
StringBuilder stringBuilder = new StringBuilder();
// Iterate through number of existing yarn application
for (int i = 0; i < j.getJSONObject("apps").getJSONArray("app").length(); i++){
JSONObject name = j.getJSONObject("apps")
.getJSONArray("app")
.getJSONObject(i);
String state = name.get("state").toString();
// Check if application is in Running state
if (state.equals("RUNNING")){
// Get elapsed time for each running application and convert it to hour
int elapsed_time = name.getInt("elapsedTime")/3600000;
// Get application name
String app_name = name.get("name").toString();
// Get application queue_name
String queue_name = name.get("queue").toString();
// Get application user_name
String user_name = name.get("user").toString();
// Check if pyspark applications last longer than specified time in config.properties
if (app_name.startsWith("pyspark-shell") && elapsed_time > getSparkCheckTime()){
String app_id = name.get("id").toString();
String infoMessageSpark = "pyspark application " + app_id + " has been killed because it takes longer than " + getSparkCheckTime() + " hours";
logger.info(infoMessageSpark);
logger.info(name.toString());
// Kill yarn application
URL url = new URL(String.format("%s%s/state?user.name=atlasapp",getUrlAddress(),app_id));
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"state\": \"KILLED\"}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
// Add info message to slackmessage string builder
stringBuilder.append(infoMessageSpark);
stringBuilder.append("\n");
}
// Check if self_bi applications last longer than specified time in config.properties
else if (!queue_name.equals("yarn-system") && !queue_name.equals("hudi") && !queue_name.equals("hepsistream") &&
!app_name.equals("Bzip2Hdfs") && !user_name.equals("spark") && !user_name.equals("yarn-ats") &&
!app_name.startsWith("pyspark-shell") && !queue_name.equals("llap") && elapsed_time > getappCheckTime()){
String app_id = name.get("id").toString();
String infoMessageSb = queue_name + " application, " + app_id + " has been killed because it takes longer than "
+ getappCheckTime() + " hours. Elapsed Time:" + elapsed_time;
logger.info(infoMessageSb);
logger.info(name.toString());
// Kill yarn application
URL url = new URL(String.format("%s%s/state?user.name=atlasapp",getUrlAddress(),app_id));
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"state\": \"KILLED\"}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
// Add info message to slackmessage string builder
stringBuilder.append(infoMessageSb);
stringBuilder.append("\n");
}
// Check if any application except hudi, llap last longer than specified time in config.properties and send them to slack channel
else if (!queue_name.equals("hudi") && !queue_name.equals("llap") && !queue_name.equals("hepsistream") &&
!queue_name.equals("yarn-system") && !user_name.equals("yarn-ats") &&
!app_name.startsWith("pyspark-shell") && !app_name.equals("Bzip2Hdfs") && !user_name.equals("spark") &&
elapsed_time > getCheckTime()){
logger.info("Application_id: " + name.get("id").toString() + " is running longer than " + getCheckTime() + " hours");
String textMessage ="Elapsed time: " + elapsed_time + " hours" + ", " +
"Application_Id: " + name.get("id").toString() + ", " +
"Username: " + name.get("user").toString() + ", " +
"Queuename:" + name.get("queue").toString() + ", " +
"Usage:" + name.get("clusterUsagePercentage").toString();
stringBuilder.append(textMessage);
stringBuilder.append("\n");
}
}
}
}
Here I would like to use some pre defined json string which will be equal to string I receive as a response using http connection. And only would like to check if - else-if conditions if they are working properly. And also would like to skip some line of code to kill some applications if conditions are met. So simply I would like to implement some assertequal method to compare infoMessage strings(which you can see in my code) only.
I found some mockito methods to mock complete method but here I want to skip some line of code inside of method and I couldnt find any example regarding this requirements. Any help and directions will be appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论