作爲Spring 3 MVC的一部分,可以將當前登錄的用戶(Principle)對象注入控制器方法。Spring 3 MVC Controller集成測試 - 將Principal注入方法
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
}
}
這被記錄爲春季3文檔這裏的一部分: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments。
這適用於生產代碼。但是我不知道如何測試這個。 當我創建集成測試(也設置了彈簧安全上下文) 並調用控制器句柄方法時,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());
... setup rest of request
ModelAndView mav = handlerAdapter.handle(request, response, controller);
.. rest of assertions
}
測試運行正常,除Principal之外的所有內容都爲空。
任何想法?
TIA
阿尤布
我試過這個,它工作。很簡單,整齊。謝謝 –