Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
Marco Prado Avatar asked Sep 17 '16 21:09

Marco Prado


People also ask

How do you test spring configuration?

You can test each configuration method with a Unit Test by using mocks, etc to check if they are OK, but the whole Spring Context thing is an Integration test. The idea is that, if you can get a Spring Context running for a Controller integration Test, then your Configurations are OK.

What does SpringBootTest annotation do?

The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. We can use the webEnvironment attribute of @SpringBootTest to configure our runtime environment; we're using WebEnvironment.

What is @ContextConfiguration in spring boot?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


1 Answers

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.

like image 109
Shady Ragab Avatar answered Oct 03 '22 06:10

Shady Ragab