我正在尝试制作一个程序,通过Web API检查公告 - 这连接到远程服务器并读取页面上的JSON - 我无法测试我的代码,因为服务器尚未生效。这会有效吗?是正确的方法吗?
public class AnnouncementChecker implements Runnable{
private final String announcementsURL = "REDACTED";
private String lastAnnouncement = "";
@Override
public void run(){
try {
URL url = new URL(announcementsURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("conditional GET");
http.setRequestProperty("Connection", "keep-alive");
http.setUseCaches(true);
http.setAllowUserInteraction(false);
if (lastAnnouncement != ""){
http.setRequestProperty("If-Modified-Since", lastAnnouncement);
}
http.setConnectTimeout(10);
http.connect();
int status = http.getResponseCode();
if (status == 304 || (status == 200 && lastAnnouncement == "")){
lastAnnouncement = http.getHeaderField("Last-Modified");
BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(json);
//String announcement = (String) jsonResponse.get("message");
//TODO What to do with announcement...
}
http.getInputStream().close();
http.disconnect();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我建议设置某种类型的测试,尽管服务器不可用。这将为您提供问题的答案,当您对代码进行更改并更改业务需求时,测试将永远存在,以保护您。
为了帮助您,我建议拆分返回响应的代码和执行解析的代码。这样,您可以独立于进行HTTP连接的部分来测试解析。
如果你不知道怎么做,那么我很乐意为你发一个例子。