Arquillian 测试 POST 到 Servlet

Arquillian test POST to Servlet

我有以下测试可用于测试 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 有一个技巧可以使它更容易。我以为有注释,但找不到任何东西。

这是我想出的:

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();
}