我的@WebMvcTest测试类如何在Spring Boot中使用此JDBC身份验证配置进行初始化?

问题描述 投票:0回答:1

我已经将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和其他依赖项使用模拟对象。

  • 自从实现上述配置以来,他们首先以this one开始崩溃……“没有可用的'javax.sql.DataSource'类型的合格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应用程序配置为使用本地数据库进行身份验证,并且可以正常工作(有一个警告,请参见我的另一个问题),但是并不是所有的测试类都可以在新的版本上正常工作...]]

spring-boot testing spring-annotations
1个回答
0
投票

使测试生效的解决方案是将此属性添加到我的@WithMockUser

application.yaml
© www.soinside.com 2019 - 2024. All rights reserved.