lundi 28 octobre 2019

How can my @WebMvcTest test classes initialize with this JDBC authentication configuration in Spring Boot?

I have configured my Spring Boot application to use a local database for authentication, and it works (with one caveat, c.f. my other question), but not all of my test classes work well with the new configuration.

Here's the relevant part of the configuration (see it all 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();
}

The test classes decorated with @SpringBootTest and @AutoConfigureMockMvc work (for example, this one). As I understand it, these ones auto-configure the various Beans of the application and test them together (a form of integration test).

I'm having trouble with the test classes decorated with @WebMvcTest (such as this one). These are supposed to test just one Controller class itself, using mock objects for the various Beans and other dependencies.

  • Since implementing the configuration above, they first started crashing with an UnsatisfiedDependencyException ... "No qualifying bean of type 'javax.sql.DataSource' available".
  • I then added these lines to each such test case:
@MockBean
private DataSource dataSource;
  • The first exception seems to go away, but now I get the following error in my logs:
    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

These tests use the @WithMockUser annotation in a few places and are not expected to use the real database or the JDBC connection, since they're each just testing a single controller.

My question: How can I use @WebMvcTest with my current security configuration without the test classes failing? Is there a convenient Spring Boot annotation I should add to the test class? Am I doing the security configuration wrong?

Aucun commentaire:

Enregistrer un commentaire