Answer the question
In order to leave comments, you need to log in
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);
}
$.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'
});
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);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question