Search code examples
javaservletstestingjboss-arquillian

Arquillian test POST to Servlet


I have the following test that works for testing a GET method on a servlet:

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

What's the best way to test a POST call to the same servlet, passing 1 parameter?

Should I be creating a WebTarget and using that or is there a trick with Arquillian that makes it easier. I thought there were annotations but can't find anything.


Solution

  • Here's what I came up with:

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