我已经使用 JavaServlet 创建了一个 Web 系统,现在想进行 JUnit 测试。我的 dataManager
只是一段提交到数据库的基本代码。如何用 JUnit 测试 Servlet?
我的代码示例,允许用户注册/注册,这是从我的主页通过 AJAX 提交:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
// Get parameters
String userName = request.getParameter("username");
String password = request.getParameter("password");
String name = request.getParameter("name");
try {
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
//pass reg details to datamanager
dataManager = new DataManager();
//store result as string
String result = dataManager.register(userName, password, name);
//set response to html + no cache
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
//send response with register result
response.getWriter().write(result);
} catch(Exception e){
System.out.println("Exception is :" + e);
}
}