Home > Enterprise >  How to disable @Configuration initialization in WebFluxTest?
How to disable @Configuration initialization in WebFluxTest?

Time:01-21

I would like to write tests for reactive controller using @WebFluxTest annotation, mocking all dependencies.

@WebFluxTest(controllers = MyController.class)
public class MyControllerTest { 
    
    @MockBean
    SomeService service;

    @Autowired
    WebTestClient webClient;

    //some tests
}

From what I understand, the WebFluxTest annotation shall apply only configuration relevant to WebFlux tests (i.e. @Controller, @ControllerAdvice, etc.), but not another beans.

My spring boot app contains a number of @Configuration classes that configure a number of beans (annotated as @Bean). Some of those configurations have also dependencies (autowired by constructor).

@Configuration
@RequiredArgsConstructor
public class MyConfig {

    private final AnotherConfig anotherConfig;

    @Bean
    //...
}

When I run my web flux tests, I can see the context initialization contains an attempt to initialize the MyConfig (and it fails because of the missing dependency which comes from 3rd party auto-configured lib). How can I configure the test to skip initialization of all of these?

I am able to exclude the problematic configuration class only by excluding auto configuration of the whole app.

@WebFluxTest(controllers = MyController.class, excludeAutoConfiguration = {MyApplication.class})
public class MyControllerTest { ... }

where MyApplication is the spring boot app autoscanning those configuration classes.

But how can I achieve to skip initialization of MyConfig only? Or even better, how can I achieve to only include a list of configurations to be initialized?

CodePudding user response:

Add

@ActiveProfiles("YOUR_ENV_OTHER_THAN_TEST")

below or above @Configuration

For multiple environments..

@ActiveProfiles(profiles ={env1, env2,env3})   
  •  Tags:  
  • Related