Как смоделировать пользовательские UserServiceDetails в SpringSecurity Bean для модульного тестирования? - PullRequest
1 голос
/ 12 октября 2019

У меня Spring Boot приложение с включенной базовой аутентификацией. UserServiceDetails потребляется из БД. В целях модульного тестирования я хочу издеваться над ним, чтобы данные использовались из других источников.

Как я могу это сделать?

Мой вопрос не в том, как издеваться UserServiceDetailsсам, но как издеваться над тем, как я могу использовать его для тестирования контроллеров с базовой аутентификацией.

Ниже приведен мой SpringSecurity config:

@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 config, чтобы я мог тестировать модули в моем приложении Spring Boot?

1 Ответ

0 голосов
/ 12 октября 2019

Я думаю, вы должны использовать @ Profile , UserDetailesService - интерфейс создает две реализации UserDetailesService, одну для теста и другую для остальной части дела

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


}

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


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...