leo
leo

Reputation: 3749

Spring Boot MockMVC Test does not load Yaml file

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.

Upvotes: 6

Views: 5626

Answers (2)

ayurchuk
ayurchuk

Reputation: 1989

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

Upvotes: 0

M. Deinum
M. Deinum

Reputation: 124546

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.

Upvotes: 8

Related Questions