Piculi
Piculi

Reputation: 13

How to get properties from .env file in spring boot test

I am trying to setup tests for my spring-boot application. In regular execution I get some values from .env file that I've specified in run configuration and get them like so:

 @Value("${jdbc.url}")
 private String jdbcUrl;

But when I try to run the simplest of tests, it fails with the exception :

Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext........ Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.url' in value "${jdbc.url}"

How do I load properties from the environment in SpringBootTest?

Here's my test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {App.class})
public class TestingWebApplicationTest {

    @Test
    public void contextLoads() {
    }

}

Upvotes: 1

Views: 1132

Answers (1)

EfeyoPixel
EfeyoPixel

Reputation: 26

Try adding your property to this location /src/test/resources/application-test.properties

Add an @ActiveProfiles("test") annotation on the test class and it should be picked up. See screenshot below;

You can use a profile specific application-{profile}.properties file

Upvotes: 1

Related Questions