0

Below is my project structure

SomeProject
    -src/main/java
    -src/main/resources
    -src/test/java
    -src/test/resources
        application-test.yml

Below are the contents of my properties file

application-test.yml

pre:
    someUrl: http://someurl

Below are the contents of the configuration class

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "pre")
public class SomeConfiguration {

    private String someUrl;

    public String getsomeUrl() {
        return someUrl;
    }

    public void setsomeUrl(String someUrl) {
        this.someUrl = someUrl;
    }
}

Below is my test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SomeConfiguration.class)
@TestPropertySource(locations = {"classpath:application-test.yml"})
public class SomeServiceTest {

    SomeObject someObject;

    @Autowired
    private SomeConfiguration someConfiguration; 

    @Test
    public void somMethodTest() {
        someObject = new SomeObject ();
        someObject.setsomeUrl(someConfiguration.getsomeUrl());

    }
}

The problem is I am getting null when I am trying to set someURL in someObject. I have seen similar questions on stackoverflow and accepted answers as well, but I am still getting null.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
TechLife
  • 173
  • 2
  • 4
  • 16

2 Answers2

0

According to the @ConfigurationProperties documentation:

Getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors.

A setter for private String sameUrl is setSameUrl and NOT setsameUrl.

So spring may read that from properties file but it cannot inject that through the setter.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
0

Unfortunately yml files are not supported with @TestPropertySource or @PropertySource.

I don't think the documentation for @TestPropertySource is clear on this fact, but the following JIRA has been closed. One of the comments says...

the locations attribute in @TestPropertySource already provides the following documentation:

Supported File Formats

Both traditional and XML-based properties file formats are supported — for example, "classpath:/com/example/test.properties" or "file:/path/to/file.xml".

The following from the spring docs spells it out for @PropertySource:

24.7.4 YAML Shortcomings

YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

You can get @PropertySource to load yaml if you create a suitable factory, not sure if you can do it with @TestPropertySource.

pcoates
  • 2,102
  • 1
  • 9
  • 20