Home > database >  How to disable springSecurityFilterChain in test case?
How to disable springSecurityFilterChain in test case?

Time:11-21

Hi I have a spring project that has spring security to authenticate users using OAUTH provider, and I have to use Spring Cloud Contract to build up a mock server for consumer testing.

repo: https://github.com/Isaacwhyuenac/spring-cloud-contract-poc/blob/main/order-service/src/test/java/com/example/producer/BaseClass.java

When I run ./gradlew clean :order-service:contractTest. The following error is thrown

delegate cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used.
java.lang.IllegalStateException: delegate cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used.

If you look at my SecurityConfig

https://github.com/Isaacwhyuenac/spring-cloud-contract-poc/blob/main/order-service/src/main/java/com/example/producer/config/SecurityConfig.java

The security filter is already setup. So, how to resolve this error and have my contractTest running properly??

CodePudding user response:

There are some issues on the BaseClass.

  1. If you are using the latest Spring Boot, use @SpringBootTest is enough. No need the @ExtendedWith
  2. Use a Mock env, set webEnvironment = Mock
  3. If you decided to use RestAssuredMockMvc, you should use this mockMvc instead of the standard MockMVC in your tests.
  4. The Mockito.reset in cleanup is no need at all.

In a WebMvc project, exclude the UserDetailsServiceAutoConfiguration and SecurityAutoConfiguration in your test context, check my example.

In a WebFlux project, just exclude ReactiveUserDetailsServiceAutoConfiguration and ReactiveSecurityAutoConfiguration and ReactiveOAuth2ResourceServerAutoConfiguration(if oauth2 resource server is enabled.) on your testing codes.

@SpringBootTest
@ImportAutoConfiguration(exclude = {ReactiveUserDetailsServiceAutoConfiguration.class, ReactiveSecurityAutoConfiguration.class})
class YourTest{
}

Or test web controller.

@WebFluxTest(controller=YourController.calss, excludeAutoConfigurations = {ReactiveUserDetailsServiceAutoConfiguration.class, ReactiveSecurityAutoConfiguration.class})
class YourTest{
}

I have created a simple Microservice sample several years ago, which used Spring Cloud Contract and Pact to implement the CDC pattern in the API testing and verify, check spring-microservice-sample.

  • Related