Percy

如何在SpringSecurity Bean中模拟自定义UserServiceDetails进行单元测试?

java

我已Spring Boot启用基本身份验证的应用程序。UserServiceDetails从数据库消耗。为了进行单元测试,我想对其进行模拟,以便从其他地方使用数据。

我该怎么做?

我的问题不是如何模拟UserServiceDetails自身,而是如何模拟使用它来通过基本身份验证测试Controller的方式。

以下是我的SpringSecurity配置:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/",
            "/csrf",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    private final static Integer bCryptEncryptionLevel = 8;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder(bCryptEncryptionLevel);
    }

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider());
        authManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers(AUTH_WHITELIST).permitAll()
                    // allow default swagger docket
                    .regexMatchers("\\A/v2/api-docs\\Z").permitAll()
                    // require auth for any other swagger docket
                    .regexMatchers("\\A/v2/api-docs?.*\\Z").authenticated()
                    .antMatchers("/**").authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

总之,我怎么能嘲笑UserServiceDetails到SpringSecurity配置,所以我能单元测试控制器到我的Spring Boot应用程序?


阅读 393

收藏
2020-12-04

共1个答案

小编典典

我认为您应该使用@Profile,这 UserDetailesService是一个接口,它创建的两个实现UserDetailesService,一个用于测试,另一个用于其余情况

@Component
@Profile("test")
public class UserDetailesServiceTestImpl implements UserDetailesService{


}

@Component
@Profile("!test")
public class UserDetailesServiceImpl implements UserDetailesService{


}
2020-12-04