What is causing my UnsatisfiedDependencyException when adding security to my Spring Boot 6 REST app tests?

251 Views Asked by At

I Have a Spring Boot 6 Rest application working and want to add unit and integration tests to it. During tests, a number of security conditions can be relaxed, specially at this moment.

So I added the following in WebSecurityConfig class to my test application:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            
            .httpBasic(withDefaults());
        return http.build();
    }
}

I expected that when the tests started to run, this security settings took place, what in fact happen. However, all tests fail because of this exception:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Unsatisfied dependency expressed through method 'setFilterChains' parameter 0: Error creating bean with name 'filterChain' defined in class path resource [br/ufpr/pessoas/config/WebSecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: Cannot read the array length because "mvcPatterns" is null

What am I missing?

1

There are 1 best solutions below

0
AlexSC On

After some work I could fix the problem, but to understand the solution it's important to understand my setting:

  1. I use VSCode with Spring Boot plug-in (company policy, don't blame me);
  2. I was running my tests from the IDE, not from Maven test (I wanted to debug a certain test);
  3. When the problem happen I had just Maven Clean my project (I had just added a new dependency to the project).

To fix the problem it's enough to run Maven test.

I noticed Maven test started to download a number of dependencies and then the tests ran with no problem. After that, running the tests from the IDE started to work again.

As a double check, I Maven cleaned the project and tried to run a test from the IDE: same problem as before. I then re-ran Maven test and again everything got back to work.