I am using Spring 3.1.0.RELEASE with Spring Security 3.1. I want to insert my Spring user (i.e., the User who is currently logging in) into the controller. I want to do it, not use
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
because it makes me easier to test the controller using JUnit. However, I had a problem with my current setup. My question is: what is the correct way to enter my user (upon request) into my controller? In my application context file, I have ...
<bean id="userDetails" class="com.myco.eventmaven.security.SecurityHolder" factory-method="getUserDetails" scope="request"> <aop:scoped-proxy /> </bean>
where I define my factory class as ...
public class SecurityHolder { @Autowired private static UserService userService; public static MyUserDetails getUserDetails() { final Authentication a = SecurityContextHolder.getContext().getAuthentication(); if (a == null) { return null; } else { final MyUserDetails reg = (MyUserDetails) a.getPrincipal(); final int userId = reg.getId(); final MyUserDetails foundUser = userService.findUserById(userId); return foundUser; }
but the factory class dies many times because "userService" cannot get auto-update (the value is always null). I am looking for the best way to do all this that can easily integrate into my JUnit test. Any ideas?
Edit : Here is the JUnit test I'm looking for work with ...
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "file:src/test/resources/testApplicationContext.xml" }) public class UserEventFeedsControllerTest extends AbstractTransactionalJUnit4SpringContextTests { private MockHttpServletRequest request; private MockHttpServletResponse response; ... @Autowired private RequestMappingHandlerAdapter handlerAdapter; @Autowired private RequestMappingHandlerMapping handlerMapping; @Before public void setUp() { ... request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); } ... @Test public void testSubmitUserEventFeedsForm() throws Exception { request.setRequestURI("/eventfeeds.jsp"); request.setMethod("POST"); final List<EventFeed> allEventFeeds = getAllEventFeeds(); request.setParameter("userEventFeeds", allEventFeeds.get(0).getId().toString()); final Object handler = handlerMapping.getHandler(request).getHandler(); final ModelAndView mav = handlerAdapter.handle(request, response, handler); assertViewName(mav, "user/eventfeeds"); }
source share