spring 3.1
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = {"classpath:root-context.xml",
- "classpath:servlet-context.xml", "classpath:security-app-context.xml"})
- public class TestSecureCtrl extends AbstractTransactionalJUnit4SpringContextTests {
- @Autowired
- private SecureCtrl controller;
- @Autowired
- private RequestMappingHandlerAdapter handlerAdapter;
- private final MockHttpServletRequest request = new MockHttpServletRequest();
- private final MockHttpServletResponse response = new MockHttpServletResponse();
- @Test
- public void testMain4User() throws Exception {
- request.setRequestURI("/secure");
- request.setMethod(HttpMethod.POST.name());
- HttpSession session = request.getSession();
- //设置springsecure的内容
- List<GrantedAuthority> ga = new ArrayList<GrantedAuthority>();
- ga.add(new GrantedAuthorityImpl("ROLE_ALL"));
- User user = new User("account", "password", true, true, true, true, ga);
- SecurityContextHolder.getContext().setAuthentication(
- new UsernamePasswordAuthenticationToken(user, null));
- session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
- ModelAndView mav = handlerAdapter.handle(request, response, new HandlerMethod(controller, "home", Model.class, HttpServletRequest.class));
- assertEquals("home", mav.getViewName());
- }
- }
spring 3.0
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = {"classpath:app-config.xml", "classpath:mvc-config.xml"})
- public class TestMainCtrl extends AbstractTransactionalJUnit4SpringContextTests {
- @Autowired
- private MainCtrl controller;
- //这种方法适用于Springframework3.0,3.1换了handler的处理类。
- @Autowired
- private AnnotationMethodHandlerAdapter handlerAdapter;
- private final MockHttpServletRequest request = new MockHttpServletRequest();
- private final MockHttpServletResponse response = new MockHttpServletResponse();
- @Test
- public void testMain4User() throws Exception {
- request.setRequestURI("/main");
- request.setMethod(HttpMethod.POST.name());
- HttpSession session = request.getSession();
- //设置 认证信息
- session.setAttribute(CommonConstants.SESSION_USER_TYPE, 1);
- session.setAttribute(CommonConstants.SESSION_USER_ID, 0);
- session.setAttribute(CommonConstants.SESSION_USER_ACC, "aa1");
- ModelAndView mav = handlerAdapter.handle(request, response, controller);
- assertEquals("/regist", mav.getViewName());
- }
- }