N
N
Nikolay Baranenko2017-06-15 10:40:46
Java
Nikolay Baranenko, 2017-06-15 10:40:46

What is the correct way to pass JSON to the post method for testing?

Hello.
Quite recently I started using JUNIT testing.
With the GET and POST methods, to which I explicitly pass which parameters, questions no longer arise.

@Test
    public void GetEmployeesServletTest() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
  when(request.getParameter("jsonData")).thenReturn(jsonData);
        when(request.getParameter("login")).thenReturn(login);
        PrintWriter writer = new PrintWriter("junit_test_POST_somefile.txt");
        when(response.getWriter()).thenReturn(writer);
        new GetEmployees().doPost(request, response);
}

BUT now it became necessary to check the operation of the POST method of the servlet, to which I give JSON in this way
$.ajax({
            type: 'POST',
            url: 'employees',
            data: JSON.stringify(json_result),
            success: function(data) {
                console.log( "Данные зафиксированы успешно.");
                },
            error: function(data) {
                console.log( "Отправка данных завершилась завершилась ошибкой: ");
        },
            contentType: "application/json",
            dataType: 'json'
        });

the POST method itself so far looks like this
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str;
        while( (str = br.readLine()) != null ){
            sb.append(str);
        }
        String output = sb.toString().replace("[", "").replace("]", "");
        try {
            JSONObject jObj = new JSONObject(output);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(output);
}

What is the correct way to write a JUNIT test to check for JSON acceptance in a servlet's POST method?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question