有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从servlet发送响应

我有一个从浏览器发送到Servlet的Ajax调用。在Servlet上计算一些值,比如A。我的问题是如何验证A。我从浏览器启动的位置使用TestNG,但在控制转移到Servlet之后。我应该如何从Servlet返回值,以便在TestNG中获取并验证它


共 (1) 个答案

  1. # 1 楼答案

    我能想到的解决方案是:

    (1) 
    

    绕过servlet:将业务计算放在一个单独的方法/类中,并直接进行测试。如果把重点放在业务代码上(而servlet层做一些琐碎的任务,比如提取简单的请求参数),这就足够了。例如:

    // logic - assuming this is the test focus, with interesting cases such as insufficient funds, limited account etc.
    public class MyBank{
       public void transferFunds(int fromAccountId, int toAccountId, int dollars)...   
    }
    // servlet that happens to have trivial code that isn't so important to test
    public class MyServlet{
        ...
             int fromAccountId=Integer.parseInt(req.getParameter("fromAccountId"));
             int toAccountId=Integer.parseInt(req.getParameter("toAccountId"));
             int dollars= Integer.parseInt(req.getParameter("dollars"));
             bank.transferFunds(fromAccountId, toAccountId, dollars)
    }
    

    (2)使用嵌入式服务器,如Jetty。 http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html 在单元测试中,您只需启动一个jetty(使用“new Server()”…)并告诉它执行servlet

    (3)还可以调用servlet,向其注入模拟请求/响应/会话等。例如,Spring有这样的模拟对象。 所以有点像:

    HttpServletRequest mockReq=new MockHttpServletRequest();
    HttpServletRequest mockResp=new MockHttpServletResponse();
    new MyServlet().service(mockReq, mockResp);
    

    只需注意,它可能需要根据servlet的需要进行一些调整——例如请求参数、会话(模拟请求有添加它们的方法)