Spring 3 MVC控制器集成测试 - 注入Principal方法 [英] Spring 3 MVC Controller integration test - inject Principal into method
问题描述
作为Spring 3 MVC的一部分,可以将当前登录的用户(Principle)对象注入到控制器方法中。
Eg
@Controller
public class MyController {
@RequestMapping(value =/ update,method = RequestMethod。 POST)
public String update(ModelMap model,Principal principal){
String name = principal.getName();
...其余的
}
}
作为Spring 3文档的一部分记录在这里:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments 。
这适用于生产代码。但是我不知道如何测试这个。
当我创建一个集成测试(也设置了spring的安全上下文)
并调用控制器句柄方法,那么Principal总是空的!
public class FareTypeControllerIntegrationTest extends SpringTestBase {
@Autowired
private MyController controller;
@Autowired
private AnnotationMethodHandlerAdapter handlerAdapter;
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test
public void testUpdate()throws Exception {
request.setRequestURI(/ update);
request.setMethod(HttpMethod.POST.name());
...设置请求的剩余
ModelAndView mav = handlerAdapter.handle(request,response,controller);
..其余的断言
}
任何想法?
p>
Ayub
request.setUserPrincipal(somePrincipal);
As part of Spring 3 MVC it is possible to inject the currently logged in user (Principle) object into a controller method.
E.g.
@Controller
public class MyController {
@RequestMapping(value="/update", method = RequestMethod.POST)
public String update(ModelMap model, Principal principal) {
String name = principal.getName();
... the rest here
}
}
This is documented as part of the Spring 3 documentation here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments.
This works in the production code. However I don't know how to test this. When I create an integration test (having set up spring security context as well) and call the controller handle method then the Principal is always null!
public class FareTypeControllerIntegrationTest extends SpringTestBase {
@Autowired
private MyController controller;
@Autowired
private AnnotationMethodHandlerAdapter handlerAdapter;
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test
public void testUpdate() throws Exception {
request.setRequestURI("/update");
request.setMethod(HttpMethod.POST.name());
... setup rest of request
ModelAndView mav = handlerAdapter.handle(request, response, controller);
.. rest of assertions
}
The tests are running correctly and everything except the Principal is null.
Any ideas?
TIA
Ayub
After a quick look into Spring sources this should work:
request.setUserPrincipal(somePrincipal);
这篇关于Spring 3 MVC控制器集成测试 - 注入Principal方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!