我有以下测试用于测试servlet上的GET方法:
@ArquillianResource
URL deploymentUrl;
@Test
@RunAsClient
public void testLoginServlet() throws IOException {
URL url = new URL(deploymentUrl, "login");
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
assertNotNull(builder.toString());
}
测试对同一个servlet的POST调用的最佳方法是什么,传递1个参数?
我是否应该创建一个WebTarget并使用它或是否有一个Arquillian的技巧,使它更容易。我以为有注释但找不到任何东西。
答案 0 :(得分:0)
以下是我提出的建议:
protected String doLoginPost(String url, String username, String password) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", username));
urlParameters.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
L.info("\nSending 'POST' request to URL : " + url);
L.info("Post parameters : " + post.getEntity());
L.info("Response Code : " +
response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() != 200) {
return null;
}
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "RESULT: ";
result.append(line);
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}