6

I have my configuration in application.yml file in the root of classpath (src/main/resources/). The configuration gets loaded fine when I start the application normally. However in my test the application.yml file gets not loaded at all.

The header of my test looks as follow:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Configuration.class)
@org.junit.Ignore
public class ApplicationIntegrationTest {

   @Inject
   private WebApplicationContext wac;

   private MockMvc mockMvc;

   @Before
   public void setup() {
       this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
   }
...

The configuration class:

@EnableAutoConfiguration
@ComponentScan("c.e.t.s.web, c.e.t.s.service")
public class Configuration extends WebMvcConfigurerAdapter {

When I debug the application I see that the yml files get loaded in ConfigFileApplicationListener, in the test however the ConfigFileApplicationListener gets not called.

leo
  • 3,677
  • 7
  • 34
  • 46
  • Because you are doing it wrong. You should use `@SpringApplicationConfiguration` instead of `@ContextConfiguration`. As explained in there [reference guide](http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications). – M. Deinum Aug 13 '15 at 11:19
  • You are right! Thanks! If you could make that an answer I'm happy to accept it. – leo Aug 13 '15 at 11:29

2 Answers2

8

There is a whole chapter in the Spring Boot Reference guide regarding testing. This section explains how to do a basic test for a Spring Boot application.

In short when using Spring Boot and you want to do a test you need to use the @ SpringApplicationConfiguration annotation instead of the @ContextConfiguration annotation. The @SpringApplicationConfiguration is a specialized @ContextConfiguration extension which registers/bootstraps some of the Spring Boot magic for test cases as well.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
0

There is a good integration between StringBoot, jUnit and YAML.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainBootApplication.class)
public class MyJUnitTests {
    ...
}


@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "section1")
public class BeanWithPropertiesFromYML {
    ...
}

For more details please check my comment here: https://stackoverflow.com/a/37270778/3634283

Community
  • 1
  • 1
ayurchuk
  • 1,879
  • 1
  • 17
  • 13