jeudi 26 novembre 2015

Mockito test returning NullInsteadOfMockException

I am trying to test my servlet for login page but the Mock test is throwing an exception

LoginServlet

/**
 * @see HttpServlet#HttpServlet()
 */
public LoginServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub

    HttpSession session = request.getSession(true);
    boolean result = false;
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    result = obj.validateLogin(username, password);
    if (result) {
        session.setAttribute("username", username);
        response.sendRedirect("UserHome.jsp");
    } else {
        response.sendRedirect("login.jsp");

    }
    return;
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

MockTest : this is the test case I have written for login

public class LoginServletMockTest {

@Test
public void testServlet() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    HttpSession session = request.getSession(true);
    when(request.getParameter("username")).thenReturn("garwitauday");
    when(request.getParameter("password")).thenReturn("123");
    when(request.getSession()).thenReturn(session);

    doNothing().when(session).setAttribute("username", "garwitauday");
    doNothing().when(response).sendRedirect("Userhome.jsp");

    LoginServlet loginservlet = new LoginServlet();
    loginservlet.doPost(request, response);

    verify(session).setAttribute("username", "garwitauday");
    verify(response).sendRedirect("Userhome.jsp");

}

}

I am not able to resolve this issue

Aucun commentaire:

Enregistrer un commentaire