spring-bootspring-testspring-boot-testspring-webspring-test-mvc

Is it possible to activate a spring profile in a WebMvcTest


Given a test class like:

@WebMvcTest
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.profiles.active=test")
public class MyControllerTest  {
... some tests
}

I get the error:

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.example.MyControllerTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]

The desired goal is that I'm just running a controller test and thus for test performance reasons do not want to set up the whole context - I just want the "web layer".

I can remove the @SpringBootTest(properties = "spring.profiles.active=test") line - however, now I've not activated the test profile, which may customise the web context in some way via properties, e.g. jackson customisations that will no longer be applied. Is there a way to get a "web layer" only test and still activate a spring profile?

My environment is java version "10.0.2" 2018-07-17, spring boot 1.5.16.RELEASE


Solution

  • To set active profile, you can use @ActiveProfiles, like this

    @WebMvcTest
    @RunWith(SpringRunner.class)
    @ActiveProfiles("test")
    public class MyControllerTest  {
    

    then you can you application-test yml or properties in test resources.