[英]Junit Test of servlet with eclipse
我不熟悉 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");
}
}
}
此 servlet 的单元测试实际上不应访问数据库。 鉴于ProfileManager
可能返回的各种结果,它应该测试 servlet 是否正确运行。
您需要使用依赖注入,以便您可以在单元测试中模拟ProfileManager
。
你如何做到这一点取决于你的框架。 在 spring 你会说:
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.