Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ConfigurationProperties in Spring with JUnit?

I have a ConfigurationProperties class and want to test it using junit. But the object is always null. What might be missing in the following code?

@EnableAutoConfiguration
@ComponentScan
@EnableConfigurationProperties(MyProperties.class)
public class AppConfig {

}

@Service
public class MyService {
    @Autowired
    private MyProperties props;

    public void run() {
        props.getName();
    }
}

@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
    private String name;
    //getter,setter
}

application.properties:

my.name=test

test:

@Configuration
@ComponentScan(basePackageClasses = {MyService.class,  MyProperties.class},
            includeFilters = @ComponentScan.Filter(value = {MyService.class,  MyProperties.class},
            type = FilterType.ASSIGNABLE_TYPE),
            lazyInit = true
)
@PropertySources(
        @PropertySource("application.properties")
    )
class AppTest {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfigTest.class)
public class MyTest extends AbstractJUnit4SpringContextTests {
    @Autowired
    private MyService service;

    @Test
    public void testService() {
        service.run();
    }
}
like image 532
membersound Avatar asked Mar 12 '15 09:03

membersound


People also ask

What is spring @ConfigurationProperties?

We use @Configuration so that Spring creates a Spring bean in the application context. @ConfigurationProperties works best with hierarchical properties that all have the same prefix; therefore, we add a prefix of mail.

How do I read test properties in spring boot?

You can use @TestPropertySource annotation in your test class. Just annotate @TestPropertySource("classpath:config/mailing. properties") on your test class. You should be able to read out the property for example with the @Value annotation.

Which annotation will set ApplicationContext for the test class with the configuration file from class path specified?

At its core, the TestContext framework allows you to annotate test classes with @ContextConfiguration to specify which configuration files to use to load the ApplicationContext for your test.


1 Answers

The following will load it for you:

@ContextConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
like image 106
Mikael Vandmo Avatar answered Oct 23 '22 21:10

Mikael Vandmo