javastruts2struts2-junit-plugin

how to post json in request in a struts2 junit4 testcase


The test looks like this :

@Test
    public void testSave() throws Exception {
        request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
        request.setContentType("application/json");
//        request.setMethod("post");

        ActionProxy proxy = getActionProxy("/save");
        actions.MyAction myAct = (actions.MyAction) proxy.getAction();

        String result = proxy.execute();

        System.out.println("test id : " + myAct.getId());
        System.out.println("test name : " + myAct.getName());

        assertEquals("success", result);

        System.out.println(response.getContentAsString());
    }

I'm trying to post a JSON to a struts2 action and I'm getting :

test id : null
test name : null

Although, if I try the same using a JSP :

test.jsp

<script>
            var data = '{"id":"1","name":"nitin"}';
            $.ajax({
                url: "http://localhost:8084/Struts2Junit4/save",
                data: data, //returns all cells' data
                dataType: 'json',
                contentType: 'application/json',
                type: 'POST',
                success: function(res) {
                    console.log(res);
                }
            });
        </script>

I get both the parameters.

I think I'm missing something in writing the test-case. Please help.


Solution

  • The JSONInterceptor looks for the content-type header that is why you need to use request.addHeader instead of request.setContentType.

    request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
    request.addHeader("Content-Type", "application/json");