我需要测试以下方法,但不能更改该方法本身。该方法向服务器发送一个POST请求,但我需要创建一个独立于服务器的测试用例。
以前我测试过类似的方法,将其重定向到一个本地文件。但是,在那种情况下,我将协议设置为文件,主机名设置为localhost,端口设置为-1。
我的问题是,该方法执行了一个POST请求并将其转换为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();
}