我已经将Spring Boot应用程序配置为使用本地数据库进行身份验证,并且可以正常工作(请注意[c0],但并非所有测试类都可以在新配置下很好地工作。
这是配置的相关部分(请参阅my other question全部:]:
here
用@Autowired
private DataSource dataSource;
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder .jdbcAuthentication()
.dataSource(dataSource)
.withUser(User.withUsername("admin").password(passwordEncoder().encode("pass")).roles("SUPER"));
logger.debug("Configured app to use JDBC authentication with default database.");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
和@SpringBootTest
修饰的测试类起作用(例如@AutoConfigureMockMvc
)。据我了解,这些自动配置应用程序的各种Bean并一起测试它们(一种集成测试)。
我在用this one]装饰的测试类上遇到麻烦(例如@WebMvcTest
)。这些应该只测试一个Controller类本身,对各种Bean和其他依赖项使用模拟对象。
UnsatisfiedDependencyException
@MockBean
private DataSource dataSource;
这些测试在某些地方使用Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: DataSource returned null from getConnection(): javax.sql.DataSource#0 bean
批注,并且不希望使用实际的数据库或JDBC连接,因为它们每个都仅测试单个控制器。
我的问题
:如何在我的当前安全配置中使用@WebMvcTest而不使测试类失败?我应该在测试类中添加方便的Spring Boot注释吗?我的安全配置做错了吗?我已经将Spring Boot应用程序配置为使用本地数据库进行身份验证,并且可以正常工作(有一个警告,请参见我的另一个问题),但是并不是所有的测试类都可以在新的版本上正常工作...]]
使测试生效的解决方案是将此属性添加到我的@WithMockUser
:
application.yaml