@Before
 public void setUp() throws Exception {
   successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
   successHandler.setDefaultTargetUrl("/logged_in.jsp");
   failureHandler = new SimpleUrlAuthenticationFailureHandler();
   failureHandler.setDefaultFailureUrl("/failed.jsp");
   SecurityContextHolder.clearContext();
 }
  @Test
  public void testStartupDetectsInvalidAuthenticationManager() throws Exception {
    AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
    filter.setAuthenticationFailureHandler(failureHandler);
    successHandler.setDefaultTargetUrl("/");
    filter.setAuthenticationSuccessHandler(successHandler);
    filter.setFilterProcessesUrl("/j_spring_security_check");

    try {
      filter.afterPropertiesSet();
      fail("Should have thrown IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
      assertEquals("authenticationManager must be specified", expected.getMessage());
    }
  }
  /** SEC-462 */
  @Test
  public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception {
    MockHttpServletRequest request = createMockAuthenticationRequest();

    MockFilterConfig config = new MockFilterConfig(null, null);
    MockFilterChain chain = new MockFilterChain(true);
    MockHttpServletResponse response = new MockHttpServletResponse();

    MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
    successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
    filter.setAuthenticationSuccessHandler(successHandler);

    filter.doFilter(request, response, chain);

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
  }
  /** SEC-1919 */
  @Test
  public void loginErrorWithInternAuthenticationServiceExceptionLogsError() throws Exception {
    MockHttpServletRequest request = createMockAuthenticationRequest();

    MockFilterChain chain = new MockFilterChain(true);
    MockHttpServletResponse response = new MockHttpServletResponse();

    Log logger = mock(Log.class);
    MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
    ReflectionTestUtils.setField(filter, "logger", logger);
    filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so");
    successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
    filter.setAuthenticationSuccessHandler(successHandler);

    filter.doFilter(request, response, chain);

    verify(logger).error(anyString(), eq(filter.exceptionToThrow));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
  }