0

I have an application with Spring Boot 1.2 and I need to use YAML configuration. I tried following settings:

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.0.RELEASE</version>
    <relativePath/>
</parent>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>

application.yml

foo:
  bar: baz

FooProperties

@Configuration
@ConfigurationProperties(prefix = "foo")
public class FooProperties {

  private String bar;
  
  // getters, setters, equals etc.

FooPropertiesConfig

@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class FooPropertiesConfig {
}

FooPropertiesTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooProperties.class)
@EnableConfigurationProperties(value = FooProperties.class)
@TestPropertySource("classpath:application.yml")
public class FooPropertiesTest extends TestCase {

    @Autowired
    private FooProperties tested;

    @Test
    public void test() {
        final String bar = tested.getBar();

        assertEquals("baz", bar);
    }
}

But bar is always null. What am I missing?

EDIT1: I tried to use old-fashion application.properties but the result is the same.

EDIT2:

I've created endpoint and it works. Problem seems to be only in my test configuration.

@RestController
public class FooController {

    @Autowired
    private FooProperties fooProperties;

    @RequestMapping("/")
    String foo() {
        return "Hello World: " + fooProperties.getBar();
    }
}

Result: Hello World: baz

JiKra
  • 1,618
  • 3
  • 29
  • 45
  • Maybe create a mock project with a more recent Spring Boot version and make that work. You should remove class `FooPropertiesConfig `, and @ContextConfiguration(classes = FooProperties.class) @EnableConfigurationProperties(value = FooProperties.class) @TestPropertySource("classpath:application.yml") and use @ActiveProfiles in your tests. It will require you to specify profiles in your application.yml – Roar S. Dec 28 '20 at 17:16
  • I think the answer [here](https://stackoverflow.com/questions/31745168/how-to-test-classes-with-configurationproperties-and-autowired) will help you. – fatih Dec 28 '20 at 17:50

0 Answers0