问题描述
我在模拟一个HttpServletRequest,在servlet调用中有新的值在请求中设置,因为使用相同的请求我们正在向一些jsp调度请求,因此请求对象被用作servlet的输入对象以及下一页的输出。
i am mocking a HttpServletRequest , in servlet call there are new values getting set in request because using same request we are dispaching request to some jsp so request object is used as a input object to servlet as well as output for next page.
我模拟了所有的输入参数,但对于所有的request.setAttribute(),我的代码什么也没做,因为它是一个模拟的类,比如我有
i mocked all input parameters , but for all request.setAttribute() , my code is doing nothing as it's a mocked class , say if i have
request.setAttribute(a,"10")
System.out.println("a = " + request.getAttribute("a"));
我得到null因为我没有给Request.getAttribute(a)任何行为,我不能,这是我对下一页的回应,所以解释我需要2个行为我的请求对象因此部分嘲笑,我到目前为止无法窥探或做任何部分嘲弄。任何想法?
i get null cuz i haven't given any behavious for Request.getAttribute("a") , and i can't , it's my response for next page , so that explain i need 2 behaviour my request object thus partial mocking , and i am unable to spy or do any partial mocking on it so far. any ideas?
代码:
//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);
}
推荐答案
您需要将属性存储到集合:
You need to store attributes into a collection :
// Collection to store attributes keys/values
final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
// Mock setAttribute
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String key = invocation.getArgumentAt(0, String.class);
Object value = invocation.getArgumentAt(1, Object.class);
attributes.put(key, value);
System.out.println("put attribute key="+key+", value="+value);
return null;
}
}).when(request).setAttribute(Mockito.anyString(), Mockito.anyObject());
// Mock getAttribute
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String key = invocation.getArgumentAt(0, String.class);
Object value = attributes.get(key);
System.out.println("get attribute value for key="+key+" : "+value);
return value;
}
}).when(request).getAttribute(Mockito.anyString());
这篇关于如何使用Mockito部分模拟HttpServletRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!