【发布时间】:2012-05-17 12:02:34
【问题描述】:
我需要在不改变方法本身的情况下测试以下方法。 该方法向服务器发出 POST 方法。但是我需要做一个独立于服务器的测试用例。
我在将其重定向到本地文件之前测试了类似的方法。 但为此,我将协议作为文件,主机名作为 localhost,端口作为 -1。
我的问题是这个方法做了一个帖子并转换为 HttpURLConnection 和 wr = new DataOutputStream(conn.getOutputStream());无法通过 http 处理本地 txt 文件。
//构造函数
public HTTPConnector(String usr, String pwd, String protocol,
String hostname, int port) {
this.usr = usr;
this.pwd = pwd;
this.protocol = protocol;
this.hostname = hostname;
this.port = port;
// connect();
}
//我需要测试的方法
public String doPost(String reference, String data) throws IOException {
URL url = null;
HttpURLConnection conn = null;
BufferedReader rd = null;
DataOutputStream wr = null;
InputStream is = null;
String line = null;
StringBuffer response = null;
url = new URL(protocol, hostname, port, reference);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic dGVzdDphc2Rm");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
// Send response
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
// Get response
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
//我可以测试的方法
public String doGet(String reference) throws IOException {
connect();
URL url = new URL(protocol, hostname, port, reference);
InputStream content = (InputStream) url.getContent();
BufferedReader xml = new BufferedReader(new InputStreamReader(content));
return xml.readLine();
}
【问题讨论】:
-
你看过使用模拟对象吗?
-
它不会去任何本地的东西,所以我发现很难重定向它。如果我能找到一种方法将其重定向到本地文件或类,那么我可以解决,但我能看到的唯一方法是制作本地服务器/线程。但这意味着我必须将我的测试定向到服务器,以便在那里获取数据,并且服务器本身需要被编程为处理请求,这比效率要高得多。
标签: java http testing post junit