2

I'm taking Software Testing because I'm majoring in CS. The professor gave us the source code of a program made in Java to test it. I'm testing right now this method:

    public static void createPanel(HttpServletRequest req, HttpServletResponse res, HttpSession hs) throws IOException
{
    String panelName = req.getParameter("panelName");
    String panelDescription = req.getParameter("panelDescription");
    int employeeID = ((EmployeeProfile)hs.getAttribute("User Profile")).EmployeeID;
    boolean result;

    //Let's validate our fields
    if(panelName.equals("") || panelDescription.equals(""))
        result =  false;
    else
        result = DBManager.createPanel(panelName, panelDescription, employeeID);
    b = result;

    //We'll now display a message indicating the success of the operation to the user
    if(result)
        res.sendRedirect("messagePage?messageCode=Panel has been successfully created.");
    else
        res.sendRedirect("errorPage?errorCode=There was an error creating the panel. Please try again.");

}

I'm using Eclipse with JUnit and mockito to test all the methods including this one. For this specific method, I want to check if the program redirects to one location or another, but I don't know how to do it. Do you have any idea? Thanks.

Luis
  • 75
  • 1
  • 7
  • [This](http://stackoverflow.com/questions/14404808/how-do-i-unit-test-httpservlet) will definitely help – sam Oct 15 '15 at 23:36
  • 1
    Pass in a mock `HttpServletResponse`, e.g. created by Mockito, and check what argument `sendRedirect` was called with. – Andy Turner Oct 15 '15 at 23:41
  • yes, i already mocked HttpServletResponse and the other parameters and passed them to this method from the unit test, but I don't know if there's any way to peek inside the HttpServletResponse class and see where it redirected – Luis Oct 15 '15 at 23:52
  • I don't think there's anything on the API that exposes this to you. Your best best is to either mock the response as already suggested, or you could do something similar to the replies on this post (extend HttpServletResponseWrapper and catch writes to the response writer) http://stackoverflow.com/questions/701681/how-can-i-read-an-httpservletreponses-output-stream – Kevin Hooke Oct 16 '15 at 00:19

1 Answers1

3

You can actually achieve it easily with Mockito and ArgumentCaptor:

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

   @Mock
   private HttpServletResponse response

   ...

   @Test
   public void testCreatePanelRedirection(){
      ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
      YourClass.createPanel(request, response, session);
      verify(response).sendRedirect(captor.capture());
      assertEquals("ExpectedURL", captor.getValue());
   }
}