Spring security SpringSecurity入口点集成测试不同于手动测试

Spring security SpringSecurity入口点集成测试不同于手动测试,spring-security,Spring Security,我已将Spring Security配置为在未经验证的用户尝试访问报告时重定向回主页。当我手动测试时,@PreAuthorize表达式触发一个AccessDeniedException,它被Spring的ExceptionTranslationFilter捕获,导致302 Found按预期重定向到主页 在我的集成测试中,异常被捕获在ExceptionTranslationFilter前面的过滤器链中的某个位置,并返回403禁止响应 applicationContext.xml摘录 为什么测试设置

我已将Spring Security配置为在未经验证的用户尝试访问报告时重定向回主页。当我手动测试时,
@PreAuthorize
表达式触发一个
AccessDeniedException
,它被Spring的
ExceptionTranslationFilter
捕获,导致302 Found按预期重定向到主页

在我的集成测试中,异常被捕获在
ExceptionTranslationFilter
前面的过滤器链中的某个位置,并返回403禁止响应

applicationContext.xml摘录
为什么测试设置会给出与手动测试不同的结果?

结果表明,我的手动测试会自动设置一个可接受的媒体类型的应用程序/pdf(我假设是由于文件扩展名)。在自动测试中,默认媒体类型接受所有。由于响应值不是PDF,因此引发了一个
HttpMediaTypeNotAcceptableException
,导致
DispatcherServlet:processHandlerException
中的异常解析程序返回空的ModelAndView并返回原始错误

/**
 * Test that the report endpoints will redirect to the home page
 */
@Test
public void testReportLoginRedirect() throws Exception {
    String endpoint = "/reports/myReportyWhichRequiresAuth.pdf";

    this.mockMvc
            .perform(get(endpoint).accept(MediaType.APPLICATION_PDF))
            .andExpect(status().isFound())
            .andExpect(redirectedUrl("http://localhost/"))
            .andReturn();

}
为了修复测试,我将接受的媒体类型设置为application/pdf,并更正了预期的重定向URL(与原始错误无关)

@Resource
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SecurityConfigTest {

    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders
                .webAppContextSetup(this.wac)
                .apply(springSecurity())
                .build();
    }

    /**
     * Test that the report endpoints will redirect to the home page
     */
    @Test
    public void testReportLoginRedirect() throws Exception {
        String endpoint = "/reports/myReportyWhichRequiresAuth.pdf";

        this.mockMvc
                .perform(get(endpoint))
                .andExpect(status().isFound()) // Error: 403 Forbidden returned
                .andExpect(redirectedUrl("/"))
                .andReturn();

    }
}
/**
 * Test that the report endpoints will redirect to the home page
 */
@Test
public void testReportLoginRedirect() throws Exception {
    String endpoint = "/reports/myReportyWhichRequiresAuth.pdf";

    this.mockMvc
            .perform(get(endpoint).accept(MediaType.APPLICATION_PDF))
            .andExpect(status().isFound())
            .andExpect(redirectedUrl("http://localhost/"))
            .andReturn();

}