I have to write a unit test for the method processRequest
in the servlet below and I'm wondering if:
It just shouldn't be done.
The class should be rewritten / refactored to allow easier unit testing. Suggestions as to how?
There is a meaningful way of getting the value of
response.getWriter().print(result)
, which is all the method returns.
Method in question:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
session = request.getSession(false);
User sessionUser = (User) session.getAttribute("user");
int userId = sessionUser.getId();
if (sessionUser != null) {
switch (request.getParameter("function")) {
// UPLOAD IMAGE FUNCTION
case "uploadimg":
// save image
final String path = getServletContext().getRealPath("") + "/resources/img/profile/tmp/";
String imagePath = imageService.uploadImage(request, path, userId);
// return image path for use in frontend java script
response.getWriter().print(getServletContext().getContextPath() + "/resources/img/profile/tmp/" + imagePath);
break;
// SAVE IMAGE FUNCTION
case "save":
// move image from temp folder to permanent storage
final String pathOrigin = getServletContext().getRealPath("") + "/resources/img/profile/tmp/";
final String pathDestination = getServletContext().getRealPath("") + "/resources/img/profile/";
boolean result = imageService.moveImage(pathOrigin, pathDestination, userId);
// Returns true whether or not the image was saved successfully
response.getWriter().print(result);
break;
}
response.getWriter().flush();
response.getWriter().close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}