我使用Java Servlets创建了一个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); …Run Code Online (Sandbox Code Playgroud) 关于使用Maven和Eclipse创建Java Web应用程序,我有几个问题:
当我在3年前探索和使用HttpUnit时,我喜欢它的功能.虽然在3年之后没有跟踪它,但当我向我的同事提出基于它的解决方案时,他告诉我它已被弃用了?apache状态告诉它处于活动状态.如果这是真的,我无法找到.如果这是真的,我会感到震惊.在错误列表中找到并且在过去1年没有找到任何受让人.我应该从这个推断中得出结论,它已被弃用了吗?
在对 SO 进行一些搜索时,我遇到了这段代码以从 URL 中提取“appUrl”:
public static String getAppUrl(HttpServletRequest request)
{
String requestURL = request.getRequestURL().toString();
String servletPath = request.getServletPath();
return requestURL.substring(0, requestURL.indexOf(servletPath));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是一个单元如何测试这样的东西?关键问题是如何创建一个HttpServletRequest用于单元测试的实例?
Fwiw我尝试了一些谷歌搜索,大多数回答都围绕着嘲笑班级。但是,如果我模拟该类以便getRequestURL返回我希望它返回的内容(举个例子,因为模拟本质上覆盖了一些返回固定值的方法),那么我当时并没有真正测试代码。我也尝试过 httpunit 库,但这也无济于事。