8

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?

Marco Prado
  • 1,208
  • 1
  • 12
  • 23

1 Answers1

7

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.

Slava Babin
  • 708
  • 2
  • 12
  • 30
Shady Ragab
  • 705
  • 10
  • 26
  • but when I remove the Configuration from my production class it picks the class with TestConfiguration – Marco Prado Sep 17 '16 at 23:08
  • how do you know that class with TestConfiguration is not picked at all..do you use a break point or print something? – Shady Ragab Sep 17 '16 at 23:14
  • I just asking because it would be a little bit tricky having the two configuration class runs because the @TestConfiguration will not replace the production class. Both of them will be working together. – Shady Ragab Sep 17 '16 at 23:17
  • If you want the two classes to replace each other, you can go with the proposed solution in my answer. – Shady Ragab Sep 17 '16 at 23:18