[英]How to send response from servlet
I have a Ajax call sent from browser to a Servlet. 我有一个从浏览器发送到Servlet的Ajax调用。 At Servlet some value is calculated say A. My query is how can I validate this A. I am using TestNG from where the browser starts but after that control shifts to Servlet.
在Servlet处,将计算一些值,例如A。我的查询是如何验证此A。我正在从浏览器启动的地方使用TestNG,但此后控件转移到Servlet。 How should I return the value from Servlet such that in TestNG I can fetch it and validate.
我应该如何从Servlet返回值,以便在TestNG中可以获取并验证。
solutions I can think of: 我能想到的解决方案:
(1)
Bypass the servlet: put your business calculations in a separate method/class, and test directly. 绕过servlet:将您的业务计算放在单独的方法/类中,然后直接进行测试。 This might be enough if the focus is on the business code (while the servlet layer does trivial tasks such as extracting simple request parameters).
如果重点放在业务代码上,这可能就足够了(而servlet层则完成了琐碎的任务,例如提取简单的请求参数)。 Eg:
例如:
// 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) Use an embedded server, like Jetty. (2)使用嵌入式服务器,例如Jetty。 http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html From your unit test you just launch a jetty (using 'new Server()'...) and tell it to execute the servlet.
http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html在单元测试中,您只需启动一个码头(使用'new Server()'...)并告诉其执行servlet。
(3) you can also invoke your servlet, injecting it with mock request/response/session etc. Spring, for example, has such mock objects. (3)您还可以调用servlet,并向其注入模拟请求/响应/会话等。例如,Spring具有这种模拟对象。 So it's something like:
就像这样:
HttpServletRequest mockReq=new MockHttpServletRequest();
HttpServletRequest mockResp=new MockHttpServletResponse();
new MyServlet().service(mockReq, mockResp);
Just note it might require some tweaking depending on what your servlet needs - eg request parameters, session (the mock request has methods to add them) 请注意,根据您的servlet的需要,可能需要进行一些调整-例如,请求参数,会话(模拟请求具有添加它们的方法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.