Здравствуйте.
Совсем надавно начал использовать JUNIT тестирование.
С методами GET и POST, которым в явном виде передаю какие параметры вопросов уже не возникает.
@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);
}
НО теперь возникла необходимость проверить работу метода POST сервлета, которому я отдаю JSON таким способом
$.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'
});
сам метод POST пока выглядит так
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);
}
Как правильно составить JUNIT тест, чтобы проверить приемку JSON в методе POST сервлета?