Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: custom properties configuration and tests

I'm using Spring Boot 2.0 with default application.yml properties file. I would like to split it to separate property files because it becomes huge.
Also I would like to write tests to check properties correctness: values that will present on production application context (not the test one).

Here is my property file: src/main/resources/config/custom.yml

my-property:
  value: 'test'

Property class:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Data
@Configuration
@ConfigurationProperties(prefix = "my-property")
@PropertySource("classpath:config/custom.yml")
public class MyProperty {

  private String value;
}

Test:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyProperty.class)
@EnableConfigurationProperties
public class MyPropertyTest {

  @Autowired
  private MyProperty property;

  @Test
  public void test() {
    assertEquals("test", property.getValue());
  }

}

But test fails with error:

java.lang.AssertionError: 
Expected :test
Actual   :null

Also I see that property value is null when running the application by printing it in ApplicationRunner.
When I used application.yml for all properties it were well with the same configuration.

How to put correct configuration for properties and tests for make it work?
Link to Github repo

like image 432
Bullet-tooth Avatar asked Jan 27 '23 23:01

Bullet-tooth


1 Answers

Finely I found the right way for having custom yaml properties in my app.

The issue is that Spring doesn't support yaml files as @PropertySource (link to issue). And here is a workaround how to deal with that described in spring documentation.
So, to be able to load properties from yaml files you need:
* To implement EnvironmentPostProcessor
* To register it in spring.factories

Please visit this github repo for complete example.

Also, thanks a lot for your support, guys!

like image 110
Bullet-tooth Avatar answered Jan 30 '23 12:01

Bullet-tooth