我正在模拟一个 HttpServletRequest ,在 servlet 调用中,请求中设置了新值,因为使用相同的请求,我们正在向某些 jsp 发送请求,因此请求对象被用作 servlet 的输入对象以及下一页的输出。
我模拟了所有输入参数,但对于所有 request.setAttribute() ,我的代码什么都不做,因为它是一个模拟类,如果我有
request.setAttribute(a,"10")
System.out.println("a = " + request.getAttribute("a"));
我得到 null 因为我没有给 Request.getAttribute(“a”) 任何行为,我不能,这是我对下一页的回应,所以解释我需要 2 行为我的请求对象因此部分模拟,我到目前为止,我无法监视或对其进行任何部分嘲笑。有任何想法吗?
代码 :
//Testcase
Myservlet.java
public void doPost(request,response)
{
String a = request.getAttribute("a");
String b = request.getAttribute("b");
int sum = Integer.parseInt(a) + Integer.parseInt(b);
request.setAttribute("sum",sum);
//well in this example i can use sum what i calculated but in real senario i can't , i have to use request.getAttribute("sum")
insertSumIntoDB(request.getAttribute("sum"));
}
}
//testMyservlet.java
@test
public void testServlet()
{
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getAttribute(a)).thenReturn("10");
when(request.getAttribute(b)).thenReturn("20");
new Myservlet(request,response);
}
原文由 Vivek 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要将属性存储到集合中: