Mockito测试返回NullInsteadOfMockException

时间:2015-11-27 03:47:37

标签: java testing mockito

我正在尝试测试我的servlet登录页面,但模拟测试正在抛出异常

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:这是我为登录编写的测试用例

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");

}

}

我无法解决此问题

1 个答案:

答案 0 :(得分:1)

也为HttpSession创建mockito对象,并在请求中设置mockito会话对象。

继续你的同样做(..)。when(..)或when(..)。thenReturn(..)来模拟调用。

确保在请求和会话对象中设置属性和参数,以便于测试。

如果你的是基于mvc的servet,那么最好使用MockMvc和它的构建器对象。