I have 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
into SpringSecurity
配置,这样我就可以将控制器单元测试到我的Spring Boot
app?
我认为你应该使用@Profile, UserDetailesService
是一个接口创建两个实现UserDetailesService
,一个用于测试,另一个用于案例的其余部分
@Component
@Profile("test")
public class UserDetailesServiceTestImpl implements UserDetailesService{
}
@Component
@Profile("!test")
public class UserDetailesServiceImpl implements UserDetailesService{
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)