メソッド自体を変更せずに次のメソッドをテストする必要があります。 このメソッドはPOSTメソッドをサーバーに作成します。しかし、私はサーバーから独立したテストケースを作る必要があります。Java JunitテストHTTP 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();
}
あなたはモックオブジェクトを使って見ましたか? – buymypies
私はそれがどのようにリダイレクトするのが難しいか分かりません。私はそれをローカルファイルやクラスにリダイレクトする方法を見つけることができる場合、私は回避策を作ることができますが、私が見ることができる唯一の方法はローカルサーバー/スレッドを作ることです。しかし、それは私がサーバーにデータを取得するために私のテストを指示しなければならないことを意味し、サーバーは自己が要求するためにハンドリングする必要があり、効率的にはるかに多くの作業が必要です。 – Gabain1993