Menu

Testing With RequestDispatcher

2011-01-13
2013-04-15
  • Nobody/Anonymous

    Hi All,

    I started using MockRunner for testing my Servlets. In one of my servlet code, I use RequestDispatcher. Following is the code snippet:
    <code>
                   protected void doPost(HttpServletRequest request, HttpServletResponse response) {

                   String result = null;
                    if (someCodition) {
    result = "/index.jsp";
    } else {
                                    result = "/welcome.jsp"
    }
    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(result);
    requestDispatcher.forward(request, response);
                  }
    </code>

    When I try to test doPost inside my test case, I don't get any output. I tried using getOutput(), getOutputAsBufferedReader() etc. Would like to know why is this so ? How can we test these scenarios ?

    Best Regards
    Narinder

     
  • Alwin Ibba

    Alwin Ibba - 2011-01-13

    Mockrunner does not execute JSPs. If your servlet writes something to its output stream you can get the output with getOutput(). JSPs are compiled to servlets and this is nothing Mockrunner is meant to do. You may test that your servlet forwarded the request to a dispatcher, that's all. Rendering JSPs is out of the scope of Mockrunner.

     
  • Narinder Kumar

    Narinder Kumar - 2011-01-13

    Hi Aibba,

    I have just started using MockRunner, so apologies in advance if asking some trivial questions. Does it mean that we will only be able to use getOutput***() methods when we are explicity writing on ServletResponse like :

    response.getWriter().write("*****")

    How can we test that our servlet forwarded the request to a dispatcher ? I tried doing something using getWebMockObjectFactory().getMockServletContext().getRequestDispatcher() but did not get the expected results.

    Many thanks in advance

    Best Regards
    Narinder

     
  • Alwin Ibba

    Alwin Ibba - 2011-01-13

    Yes to your first question with the ServletResponse.

    MockServletContext has methods like getRequestDispatcherMap() and getRequestDispatcher(String). You can get the MockRequestDispatcher fpr your JSP with these methods. MockRequestDispatcher itself has methods getForwardedRequest, getPath etc. Have a look at the source code of MockServletContext if you are in doubt.

     
  • Narinder Kumar

    Narinder Kumar - 2011-01-13

    Hi Abiba,

    Many thanks for your response. I was able to test using your suggested approach.

    Best Regards
    Narinder

     

Log in to post a comment.

MongoDB Logo MongoDB