介绍
我有一个 Java/Tomcat/Spring 2.5/Spring Webflow 2.0.9 Web 应用程序。为了测试一些页面,我创建了 JUnit 测试,它为表单对象设置值并模拟来自浏览器的请求。JUnit 测试类看起来像这样:
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
@ContextConfiguration(locations = { "classpath:/WebTests-context.xml", "classpath:/messageSourceConfig.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class InitechValidatorTests {
protected MockHttpSession session;
protected MockHttpServletRequest request;
//test methods omitted
protected void startSession() {
session = new MockHttpSession();
}
protected void endSession() {
session.clearAttributes();
session = null;
}
protected void startRequest() {
request = new MockHttpServletRequest();
request.setSession(session);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
MockRequestContext mrc = new MockRequestContext();
org.springframework.webflow.execution.RequestContextHolder.setRequestContext(mrc);
MessageContext messageContext = org.springframework.webflow.execution.RequestContextHolder.getRequestContext()
.getMessageContext();
this.validationContext.setMessageContext(messageContext);
}
protected void endRequest() {
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).requestCompleted();
RequestContextHolder.resetRequestAttributes();
request = null;
org.springframework.webflow.execution.RequestContextHolder.setRequestContext(null);
}
}
对于每个测试方法,我调用 startRequest 和 endRequest 方法(在第一个测试方法之前调用 startSession,在最后一个测试方法之后调用 endSession)。如果没有这个构造,我将无法在我正在测试的代码中使用例如 RequestContextHolder。
问题
在要测试的类中,我从 Web 流中读取请求参数的内容,如下所示:
RequestContext requestContext = RequestContextHolder.getRequestContext();
ExternalContext externalContext = requestContext.getExternalContext();
String printPressed = externalContext.getRequestParameterMap().get("printPressed");
我需要在我的 JUnit 测试方法中设置“printPressed”请求参数,如下所示:
org.springframework.webflow.execution.RequestContext requestContext = org.springframework.webflow.execution.RequestContextHolder
.getRequestContext();
ExternalContext externalContext = requestContext.getExternalContext();
Map requestParamMap = externalContext.getRequestParameterMap().asMap();
requestParamMap.put("printPressed", "true");
然而,这是不可能的,因为映射是不可变的并且会导致 UnsupportedOperationException。
问题是:如何在org.springframework.webflow.context.ExternalContext类中为 requestParameterMap 设置请求参数?getRequestParameterMap返回的参数映射是不可变的,所以我不能在那里添加参数。我注意到有一个对象MockParameterMap,这听起来很有希望:“允许参数突变的参数映射的扩展。可用作测试的存根。”
如何将 MockParameterMap 注入测试类中的 ExternalContext?还是有其他方法可以设置单元测试的请求参数?