在单元控制器测试中配置MockHttpServletRequest

时间:2013-06-25 17:37:09

标签: unit-testing spring-mvc mocking spring-test

我正在尝试使用MockHttpServletRequest将参数附加到会话,但只在我的测试中声明了一个属性我收到了以下错误:

Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

我尝试添加<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>,就像在此链接中说:Getting a 'No thread-bound request found' error from spring in my web app

测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = WebContextLoader.class, classes = { TestApplicationWebContext.class })
public class ClienteControllerTest {

private MockMvc mockMvc;

@Resource
private WebApplicationContext webApplicationContext;

@Autowired
private org.springframework.mock.web.MockHttpServletRequest request;

@Before
public void inicializacao() {
    mockMvc = MockMvcBuilders.webApplicationContextSetup(webApplicationContext).build();
}

@Test
public void teste() throws Exception {
    mockMvc.perform(get("/administracao/cliente")).andExpect(status().isOk()).andExpect(forwardedUrl("administracao-cliente/index"));
}

}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

web.xml中配置一个监听器对Spring MVC Test框架的集成测试没有影响,因为那些测试在Servlet容器之外运行

我显然没有看到你试图测试的控制器代码,但如果你可以升级到Spring 3.2,我相信这应该是开箱即用的,这要归功于默认注册的ServletTestExecutionListener 。这与Spring 3.2中引入的新@WebAppConfiguration注释的支持一起使用。有关详细信息,请参阅reference manual中的示例。

如果这对您不起作用,请更详细地考虑creating a test case that reproduces the error和/或opening a JIRA issue描述您的问题。

干杯,

萨姆