测试 WebSecurityConfigurerAdapter

Testing WebSecurityConfigurerAdapter

这是我的测试,我正在添加额外的 header 测试

@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@EnableWebMvcSecurity
@SpringApplicationConfiguration( classes = {
        MockServletContext.class,
        HttpSessionConfig.class,
        WebSecurityConfig.class
} )
@SuppressWarnings( "PMD.TooManyStaticImports" )
public class HeadersTest {

    private MockMvc mockMvc = null;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup( context )
                .addFilter( new CORSFilter(), "/*" )
                .build();
    }

    @Test
    public void testOptions() throws Exception {
        mockMvc.perform( options( "/" ) )
                .andExpect( status().is2xxSuccessful() )
                .andExpect( header().string( "Access-Control-Allow-Origin", notNullValue() ) )
                .andExpect( header().string( "Access-Control-Allow-",
                        equalToIgnoringCase( "POST, GET, PUT, OPTIONS, DELETE" ) ) )
                .andExpect( header().string( "Access-Control-Allow-Headers",
                        equalToIgnoringCase( "content-type, x-auth-token, x-requested-with" ) ) )
                .andExpect( header().string( "Access-Control-Expose-Headers", equalToIgnoringCase( "Location" ) ) )
                .andExpect( header().string( "Access-Control-Max-Age", notNullValue() ) )
        ;
    }    
}

如果我从配置中删除 WebSecurityConfig.class,则测试有效,但是当我添加它时,出现此异常

 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor]

这是WebSecurityConfig

@Configuration
@Order( SecurityProperties.BASIC_AUTH_ORDER - 1 )
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure( final HttpSecurity http ) throws Exception {
        http.httpBasic().and()
                .authorizeRequests()
                .antMatchers( "/" ).permitAll()
                .anyRequest().authenticated();
    }
}

我怎样才能更改我的测试以使 WebSecurityConfig 正确?

这似乎有效,但似乎重得多,所以也许他们是 lighter/faster 答案?

我加了

@SpringBootApplication
public class Application {
}

并加载它,以及添加 @WebAppConfiguration 和我的 WebSecurityConfig 类,

@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@SpringBootApplication
@SpringApplicationConfiguration( classes = {
        MockServletContext.class,
        HttpSessionConfig.class,
        WebSecurityConfig.class,
        Application.class
} )
public class HeadersTest {

现在测试再次通过,同时添加了一个检查 X-Frame-Options

的测试