Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot tests - Can't find test properties

Tags:

I have a spring boot project and it works great. I now want to write tests for my application and I am running into some configuration headaches.

Spring boot created a test class for me called ApplicationTests. It's real simple and it looks like this:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DuurzaamApplicationTests {
    @Test
    public void contextLoads() {
    }    
}

Now when I start the tests I get this error:

java.lang.IllegalArgumentException: Could not resolve placeholder 'company.upload' in value "${company.upload}"

I have a properties.yml file in the src/test/resources directory and for some reason it isn't loaded. I have tried all different kind of annotations from examples on the Internet and yet none of them work.

How can I tell spring boot tests to use an application.yml file to load the properties from?

like image 424
Martijn Hiemstra Avatar asked Aug 13 '17 10:08

Martijn Hiemstra


People also ask

Where does spring boot look for property file in test?

properties file in the classpath (src/main/resources/application. properties).

How do I get spring boot properties?

Another way to read application properties in the Spring Boot application is to use the @ConfigurationProperties annotation. To do that, we will need to create a Plain Old Java Object where each class field matches the name of the key in a property file.

What is SpringBootTest annotation?

@SpringBootTest is a primary annotation to create unit and integration tests in Spring Boot applications. The annotation enables additional features such as custom environment properties, different web environment modes, random ports, TestRestTemplate and WebTestClient beans.


1 Answers

We can use @TestPropertySource or @PropertySource to load the properties file.

Example:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:properties.yml")
@ActiveProfiles("test")
public class DuurzaamApplicationTests {
    @Test
    public void contextLoads() {
    }    
}

Docs: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html

like image 73
Barath Avatar answered Oct 19 '22 11:10

Barath