首页 > 解决方案 > Spring Boot Http Security 配置单元测试

问题描述

在我的 Spring 引导应用程序中,我有一个安全配置类,我正在尝试为其编写单元测试。这是我第一次这样做,所以我需要一些帮助。这是下面的代码。请一些帮助将不胜感激。谢谢

public class SecurityConfig extends WebSecurityConfigurerAdapter {

private String id;
private String pwd;
private String role;

@Autowired
private AuthenticationEntryPoint authEntryPoint;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .anyRequest().authenticated()
            .and().httpBasic()
            .authenticationEntryPoint(authEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    //This allows to view h2 console during development
    http.headers().frameOptions().sameOrigin();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().
            withUser(id).
            password(pwd).
            roles(role);
}}

标签: javaspringspring-bootspring-security

解决方案


我不建议为配置类本身编写单元测试。通常,证明您的应用程序功能的集成测试(例如使用Mock MVC)效果最好。

我意识到这不是你问的;然而,如果你看一下 spring security repo,你会发现他们也是这样做的。即,为了测试他们的配置器,他们使用集成测试


推荐阅读