Marco Prado Marco Prado - 1 month ago 23
Java Question

Spring boot test configuration not being picked

I am writing an integration test for my application, and want to use a custom webmvc configuration for my tests

I have three classes in my base package com.marco.nutri:


  • Application(which is annotated with @SpringBootApplication)

  • MvcConfig(@Configuration and @EnableWebMVC)

  • SecurityConfig(@Configuration and @EnableWebSecurity)



My test is in the package br.com.marco.nutri.integration.auth:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class, WebMvcTestConfiguration.class, SecurityConfig.class})
public class ITSignup {

//Test code

}


I have a test config class in the package com.marco.nutri.integration:

@TestConfiguration
@EnableWebMvc
public class WebMvcTestConfiguration extends WebMvcConfigurerAdapter {
//Some configuration
}


But when I run my test, the MvcConfig.class is picked instead of WebMvcTestConfiguration.class

What am I doing wrong?

Answer

you can annotate your test configuration with @Profile("test") and your real one with @Profile("production")

and in your properties file put the property spring.profiles.active=production and in your test class put @Profile("test"). So when your application starts it will use "production" class and when test stars it will use "test" class.

from documentation

Unlike regular @Configuration classes the use of @TestConfiguration does not prevent auto-detection of @SpringBootConfiguration.

Unlike a nested @Configuration class which would be used instead of a your application’s primary configuration, a nested @TestConfiguration class will be used in addition to your application’s primary configuration.

Comments