@Test
public void testHttpHeaderAuthenticationFilterWithDatabaseConnectionError() throws Exception
{

    setupTestFunctions("testRole");
    modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariables());
    ApplicationUserBuilder applicationUserBuilder =
        (ApplicationUserBuilder) ReflectionTestUtils.getField(httpHeaderAuthenticationFilter, "applicationUserBuilder");
    try
    {
        MockHttpServletRequest request =
            getRequestWithHeaders(USER_ID, "testFirstName", "testLastName", "testEmail", "testRole", "Wed, 11 Mar 2015 10:24:09");
        ApplicationUserBuilder mockApplicationUserBuilder = Mockito.mock(ApplicationUserBuilder.class);
        Mockito.when(mockApplicationUserBuilder.buildNoRoles(any(HttpServletRequest.class))).thenThrow(PersistenceException.class);
        // Invalidate user session if exists.
        invalidateApplicationUser(request);
        ReflectionTestUtils.setField(httpHeaderAuthenticationFilter, "applicationUserBuilder", mockApplicationUserBuilder);
        httpHeaderAuthenticationFilter.init(new MockFilterConfig());
        MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
        httpHeaderAuthenticationFilter.doFilter(request, mockHttpServletResponse, new MockFilterChain());
        assertEquals(500, mockHttpServletResponse.getStatus());
        ErrorInformation errorInformation = new ErrorInformation();
        errorInformation.setStatusCode(500);
        errorInformation.setStatusDescription("Internal Server Error");
        errorInformation.setMessage("javax.persistence.PersistenceException");
        errorInformation.setMessageDetails(new ArrayList<>());
        assertEquals(xmlHelper.objectToXml(errorInformation), mockHttpServletResponse.getContentAsString());
    }
    finally
    {
        restorePropertySourceInEnvironment();
    }
    // reset application user builder
    ReflectionTestUtils.setField(httpHeaderAuthenticationFilter, "applicationUserBuilder", applicationUserBuilder);
}