我有一个从浏览器发送到Servlet的Ajax调用。我应该如何从Servlet返回值,以便在TestNG中可以获取并验证它。
发布于 2015-04-27 17:38:07
我能想到的解决方案:
(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 (使用'new Server()'...)并告诉它执行servlet。
(3)你也可以调用你的servlet,给它注入模拟请求/响应/会话等。所以它是这样的:
HttpServletRequest mockReq=new MockHttpServletRequest();
HttpServletRequest mockResp=new MockHttpServletResponse();
new MyServlet().service(mockReq, mockResp);只需注意,它可能需要根据servlet的需要进行一些调整-例如,请求参数、会话(模拟请求具有添加它们的方法)
https://stackoverflow.com/questions/29891250
复制相似问题