首页 > 解决方案 > 用eclipse对servlet进行Junit测试

问题描述

我不熟悉 Junit 测试。例如,如何为这个 servlet 编写单元测试?我真的不知道从哪里开始,拜托!!!显然他访问数据库,我不知道如何进行测试以检查输入的凭据是否存在于数据库中。你能给我一个关于这个servlet的例子吗?

/**
 * Servlet implementation class LoginPatient
 */
@WebServlet("/LoginPatient")
public class LoginPatient extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fiscal_code=request.getParameter("fiscal_code");
        String user_password= request.getParameter("user_password");
        PrintWriter out=response.getWriter();
        ProfileManager pM=new ProfileManager();
        UserBean patient= pM.ReturnPatientByKey(fiscal_code, user_password);

        if(patient != null) {
            HttpSession session= request.getSession();
            session.setAttribute( "user" , patient);
            session.setMaxInactiveInterval(-1);
            out.println("1");
        }

        else {
            out.println("0"); 
        }
    }

}

标签: javaservletsjunit

解决方案


此 servlet 的单元测试实际上不应访问数据库。ProfileManager考虑到可能返回的各种结果,它应该测试 servlet 的行为是否正确。

您需要使用依赖注入,以便可以ProfileManager在单元测试中进行模拟。

你如何做到这一点取决于你的框架。春天你会说:

@Component
public class LoginPatient extends HttpServlet {
   ...
   @Autowired
   public LoginPatient(ProfileManager profileManager) { ... }
   ...
}

然后在您的测试中使用 Mockito(这是一个草图不可编译的代码)

public void testPresent() {
   // mock the request and response, and the session
   HttpServletRequest req = mock(HttpServletRequest.class);
   Session session = mock(HttpSession.class);
   when(req.getSession()).thenReturn(session);
   ...
   // you might want to mock the UserBean instance too
   ProfileManager pm = mock(ProfileManager.class);
   when(pm.ReturnPatientByKey("aCode", "aPassword")).thenReturn(new UserBean(...));
   LoginPatient servlet = new LoginPatient(pm);
   servlet.doPost(req, res);
   // verify that the session had the right things done to it
}

推荐阅读