【问题标题】:Junit Test of servlet with eclipse用eclipse对servlet进行Junit测试
【发布时间】:2021-01-29 22:33:20
【问题描述】:

我不熟悉 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"); 
        }
    }

}

【问题讨论】:

    标签: java servlets junit


    【解决方案1】:

    此 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 2012-02-05
      • 2016-11-16
      • 2015-07-08
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多