HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Unit testing a servlet in a meaningful way

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
waytestingservletmeaningfulunit

Problem

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();
}
}

@Ove

Solution

Bug: You're verifying if sessionUser is different from null, but you're doing sessionUser.getId() before you're sure if it's null or not. If it was null, doing getId would have thrown a NullPointerException

int userId = sessionUser.getId();

if (sessionUser != null) {

Code Snippets

int userId = sessionUser.getId();

if (sessionUser != null) {

Context

StackExchange Code Review Q#63053, answer score: 2

Revisions (0)

No revisions yet.